I'm trying to create a userscript that will search inside a div for a specific text string and if it's available, click a specific radio button inside that specific div. There is usually multiple div per page that will each need to be individually processed. I've tried various scripts with both next() and nextAll(), but I have not come even close to getting it working. Any help would be greatly appreciated. Here is an example of how the intended page is coded:
<div class="block">
<div>
<div class="place">Text to be searched
</div>
<div class="place">
<div id="question">
<input value="yes">
<input value="no">
</div>
</div>
</div>
</div>
Multiple times, up to 3. I'm new to javascript/jquery, could anyone please point me in the direction to get something like this working? Thank you!
Edit: Thanks to a very useful comment, I managed to get it working exactly how I needed it to like this:
var arr = ['Keyword1', 'Keyword2', 'Keyword3'];
var i=0;
for (; i<arr.length; i++) {
$("div div.place.bg-dark:contains('"+arr[i]+"')").each(function() {
$(this).nextAll().find('input[type=radio][value=2]').click();
$(this).parent().parent().css("cssText", "border: 15px solid red !important;");
});
}
Use .filter()
to filter out the text div or question divs and then use .next('div.place')
to find and mark checked the desired radio
button.
See demo below
var textToSearch = 'Text to be searched';
var valueToCheck='yes';
$(document).ready(function() {
$(".block div.place").filter(function() {
return $.trim($(this).text()) == textToSearch;
}).next('div.place').find('input[type="radio"][value="'+valueToCheck+'"]').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block">
<div>
<div class="place">Text to be searched</div>
<div class="place">
<div id="question">
<input type="radio" value="yes">
<input type="radio" value="no">
</div>
</div>
</div>
<div>
<div class="place">Text to be searched
</div>
<div class="place">
<div id="question">
<input type="radio" value="yes">
<input type="radio" value="no">
</div>
</div>
</div>
</div>