开发者

Jquery conditional statement

开发者 https://www.devze.com 2023-02-14 10:53 出处:网络
My html <tr id=\"uniqueRowId\"> <td> <input class=\"myChk\" type=\"checkbox\" /> </td>

My html

<tr id="uniqueRowId">
    <td>
        <input class="myChk" type="checkbox" />
    </td>
    &l开发者_如何学编程t;td class="from">
        <textarea class="fromInput" ...></textarea>
    </td>
    <td class="to">
        <textarea ...></textarea>
    </td>
</tr>

I have a table where each row is similar to the above with only one exception: not all rows will have textreas. I need to grab all rows that have textareas AND checkbox is not "checked".

Then I need to leaf through them and do some stuff. I tried something like:

   var editableRows = $("td.from .fromInput");
    for (s in editableRows)
    {
       $s.val("test value");
    }

but it didn't work.

1) how do I grab ONLY the rows that have checkboxes off AND have fromInput textareas? 2) how do I leaf through them and access the val() of both textareas?


I am sure this could be optimized, but I think it will work.

$("tr:not(:has(:checked))").each(function(i, tr) {
   var from = $(tr).find("td.from textarea").val();
   var to = $(tr).find("td.to textarea").val();

   //now do something with "from" and "to"
});

See it working on jsFiddle: http://jsfiddle.net/RRPqb/


You can use this to select the rows:

$('tr', '#yourTable').has('input:checkbox:not(:checked)').has('textarea')

Live demo: http://jsfiddle.net/simevidas/Zk5EH/1/

As you can see in the demo, only the row that has a TEXTAREA element and a unchecked checkbox will be selected.


However, I recommend you to set classes to your rows: the TR elements that contain TEXTAREA elements should have a specific class set - like "directions". Then you could select those rows easily like so:

$('tr.directions', '#yourTable').each(function() {
    if ( $(this).find('input:checkbox')[0].checked ) return;  

    // do your thing
});


$("tr:not(:has(:checked)):has(input.fromInput)")

Should be what you need. All the rows that don't have anything checked but that do have an input with the class 'fromInput'

If you want to loop through them to get the value of any textarea just extend your selector:

$("tr:not(:has(:checked)):has(textarea.fromInput) textarea")

Or as above if you want to be able to distinguish them:

$("tr:not(:has(:checked)):has(textarea.fromInput)")
  .each(function() {
    var from = $(this).find("td.from textarea").val();
    var to = $(this).find("td.to textarea").val();
  })

I don't know how much performance is a concern here, but if it is, then rather then writing a selector to find rows that contain a textarea you may find it helps to add a class to the row itself.

<tr class="hasTextarea">

Then you could alter your JQuery as so:

$("tr.hasTextarea:not(:has(:checked))")
0

精彩评论

暂无评论...
验证码 换一张
取 消