Fish
Fish

Reputation: 225

How to get a form element that has a dynamic ID - Need to get the element with the highest ID

I have a form with check boxes that are populated dynamically resulting in something like the following:

<input type="checkbox" name="1-subject" value="Option A" class="check" id="id_1-subject_0">
<input type="checkbox" name="1-subject" value="Option B" class="check" id="id_1-subject_1">
<input type="checkbox" name="1-subject" value="Other:" class="check" id="id_1-subject_2">

<input type="text" name="1-subject_other" id="id_1-subject_other" class="text" onkeyup="Test();" >

If I need the "Other:" checkbox to be automatically checked if anything is typed in the text field I could do this:

<script>
function Test(){
    var a = document.getElementById("id_1-subject_other");
    var b = document.getElementById("id_1-subject_2");
    if (!a) {
        b.checked=true;
    }
}
</script>

However if another option is added, the 'Other:' checkbox will change to id_1-subject_3. How would I get this field by the dynamically changing ID as var b? Or can I get by value of 'Other:'?

Upvotes: 0

Views: 135

Answers (3)

mountain_hawk
mountain_hawk

Reputation: 41

You can do it with jQuery by value.

$("input[type=checkbox][value='Other:']").prop("checked",true);

Upvotes: 0

Tom&#225;s
Tom&#225;s

Reputation: 3561

As the value of the "Other:" input will not change, you can use:

document.querySelector('input[value="Other:"]')

and get the element.

Upvotes: 1

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

You can get dom using document.querySelector('input[name=other]') on keyup event.

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

DEMO

function Test(el){
  document.querySelector('input[name=other]').checked= el.value!='';
}
<input type="checkbox" name="1-subject" value="Option A" class="check" id="id_1-subject_0"><label>A</label><br>
<input type="checkbox" name="1-subject" value="Option B" class="check" id="id_1-subject_1"><label>B</label><br>
<input type="checkbox" name="other" value="Other:" class="check" id="id_1-subject_2"><label>Other</label><br>

<input type="text" name="1-subject_other" id="id_1-subject_other" class="text" onkeyup="Test(this);">

Upvotes: 0

Related Questions