I want to check a checkbox based on the values from another div
. For example, I want the checkbox to be checked if this page has text name title
. If it doesn't have a title
then the checkbox won't be checked.
<div class="testdiv">
<p>title</p>
</div>
<div class="checkbox">
<input type="checkbox" name="testcheck" id="testcheck" value="1">
<label for="testcheck">Lorem Ipsum</label>
</div>
I suggest this way:
if ($('#testdiv > p:contains("title")').length > 0) {
$("#testcheck").prop('checked', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="testdiv">
<p>title</p>
</div>
<div class="checkbox">
<input type="checkbox" name="testcheck" id="testcheck" value="1">
<label for="testcheck">Lorem Ipsum</label>
</div>
Basically you are already checking over the selector, if the p contains any text, and then set the checkbox true.
Working testcase:
var val = $('.testdiv').find('p').text(); if (val == 'title') { $('#testcheck').prop('checked', true) } else { $('#testcheck').prop('checked', false) }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="testdiv"> <p>title</p> </div> <div class="checkbox"> <input type="checkbox" name="testcheck" id="testcheck" value="1"> <label for="testcheck">Lorem Ipsum</label> </div>
Try this way
first get the text of the p. the text you want to compare. then use if condition to compare if true use .prop()
to set the checkbox to checked
This should be enough:
if($('div').text().indexOf('title')!=-1)
// check the checkbox
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.