I am loading a page through a div because of iframe restrictions. What I want to do is access the page contents and select the first item in the dropdown. If the id of the dropdown is called myDropdown or something like "ctl00_ctl65_g_549adf60_cb6b_4794_af15_99ce724b040f_FormControl0_V1_I1_D2", how do i access this to select.
$(document).ready(function() {
$("#load_home").on("click", function() {
$("#content").load("https://page.aspx");
});
});
<div id="topBar">
<a href="#" id="load_home"> Rate!</a>
</div>
<div id="content">
</div>
Try this script.
var interval;
$(document).ready(function () {
$("#load_home").on("click", function () {
$('.calc-loader').show();
$("#content").load("HtmlPage5.html");
interval = setInterval(function () {
console.log($('#content select option').length);
if ($('#content select option').length > 2) {
clearInterval(interval);
$('.calc-loader').hide();
$('#content select option:eq(3)').prop("selected",true);
$('#content select').trigger('change');
}
}, 1000);
});
});
You need to access it in the .load callback or delegate:
$(function() {
$("#load_home").on("click", function() {
$("#content").load("https://page.aspx",function() {
$("#myDropdown option:eq(2)").prop{"selected",true);
// if you have event handlers on the select, you want to trigger them
$("#myDropdown").change();
});
});
});
Delegation:
$("#content").on("change","#myDropdown",function() {
// delegated the change event to the container
});
Here is a modular findAndSelect() function using pure JS. Parameters are the string ID of the select, and the string value of the option you want to select.
Say your html is : <select id="sel"><option>option1</option></select> and you want to set #sel to 'option1', you call findAndSelect('sel','option1');
function findAndSelect (elementId, optionToSelect) {
function findRelevantIndex(elementId) {
var optionsArr = document.getElementById(elementId).options;
var optionsLen = optionsArr.length;
for (var i = 0; i < optionsLen; i++) {
if (optionsArr[i].text == optionToSelect) {
return i;
}
}
console.log('found no matching option as ' + optionToSelect);
return 0;
}
document.getElementById(elementId).selectedIndex = findRelevantIndex(elementId);
console.log('new selected index for ' + elementId + ' is ' + document.getElementById(elementId).selectedIndex);
}