Search code examples
javascriptjqueryjsgrid

How to get and set different values of two jquery nodes?


I have two jquery nodes:

$result = this._editTime = 
             $("<input>")
               .attr({"type":"number", "style":"display:inline;", "min":"0"})
               .add("<span>&nbsp;d&nbsp;<span>")
               .add("<input type='number' style='display:inline;' , min='0'></input>")
               .add("<span>&nbsp;h&nbsp;<span>");

I want to set initial value for both input field, and get the modified value. if I use

$result.val(value) 

The value of 2 inputs will be the same, but I want to set different to them. And I also tried:

$result.siblings("input")[0].value = days;
$result.siblings("input")[1].value = hours;

But system said : Uncaught TypeError: Cannot read property 'val' of undefined.

However, I can read value through this method, but the value is not what I modified.

So, how can I set the initial value(different) for this two input fields and get the new value I changed?

Here is the fiddle of the application, you can see the prolme in "Time" column. When I click the row to edit, and the value will disappear and I cannot modified the value as well. http://jsfiddle.net/codingbunny/p39kteqh/7/

Any advice will be appreciated.

Thank you very much!


Solution

  • You know the indexes of the elements you need to access because you just built the jQuery object. Just access the <input>s directly:

    $result[0].value = days;
    $result[2].value = hours;
    

    Example:

    var $result = $("<input>").attr({
      "type": "number",
      "style": "display:inline;",
      "min": "0"
    }).add("<span>&nbsp;d&nbsp;<span>").add("<input type='number' style='display:inline;' , min='0'></input>").add("<span>&nbsp;h&nbsp;<span>");
    
    var days = 1;
    var hours = 2;
    
    $result[0].value = days;
    $result[2].value = hours;
    
    $(document.body).append($result);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>