selecting the dropdown from an page loaded through a div - javascript

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">
Rate!
</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);
});
});

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);
}

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
});

Related

Dropdown Value selected not changing when option selected changes Java Script

Following is Html for Drop down
<select name="fancySelect" onchange="test()" class="makeMeFancy" id="drop1">
<option value="0" selected="selected" data-skip="1" data-icon="assets/images/large/bitcoin.png" data-html-text="BTC<i&gt">BTC<span class="select_coin_button_arrow">▾</span></option>
<option value="1" data-icon="assets/images/small/bitcoin.png" data-html-text="BTC<i&gt" >BTC</option>
<option value="17" data-icon="assets/images/small/ether.png" data-html-text="ETH<i>">ETH</option>
</select>
and following is js function test()
function test() {
var e = document.getElementById("drop1");
var strUser = e.options[e.selectedIndex].value;
console.dir(strUser)
}
How to Print
Follwing is Jquery Script working on Dropdown
As code is working without Jquery Script,There seems to be problem
in following JQuery
$(document).ready(function () {
// The select element to be replaced:
var select = $('select.makeMeFancy');
var selectBoxContainer = $('<div>', {
width: select.outerWidth(),
className: 'tzSelect',
html: '<div class="selectBox"></div>'
});
var dropDown = $('<ul>', {className: 'dropDown'});
var selectBox = selectBoxContainer.find('.selectBox');
// Looping though the options of the original select element
select.find('option').each(function (i) {
var option = $(this);
if (i == select.attr('selectedIndex')) {
selectBox.html(option.text());
}
// As of jQuery 1.4.3 we can access HTML5
// data attributes with the data() method.
if (option.data('skip')) {
return true;
}
// Creating a dropdown item according to the
// data-icon and data-html-text HTML5 attributes:
var li = $('<li>', {
html: '<img src="' + option.data('icon') + '" /><span>' +
option.data('html-text') + '</span>'
});
li.click(function () {
selectBox.html(option.text());
dropDown.trigger('hide');
// When a click occurs, we are also reflecting
// the change on the original select element:
select.val(option.val());
return false;
});
dropDown.append(li);
});
selectBoxContainer.append(dropDown.hide());
select.hide().after(selectBoxContainer);
// Binding custom show and hide events on the dropDown:
dropDown.bind('show', function () {
if (dropDown.is(':animated')) {
return false;
}
selectBox.addClass('expanded');
dropDown.slideDown();
}).bind('hide', function () {
if (dropDown.is(':animated')) {
return false;
}
selectBox.removeClass('expanded');
dropDown.slideUp();
}).bind('toggle', function () {
if (selectBox.hasClass('expanded')) {
dropDown.trigger('hide');
}
else dropDown.trigger('show');
});
selectBox.click(function () {
dropDown.trigger('toggle');
return false;
});
// If we click anywhere on the page, while the
// dropdown is shown, it is going to be hidden:
$(document).click(function () {
dropDown.trigger('hide');
});
});
$(document).ready(function () {
// The select element to be replaced:
var select = $('select.makeMeFancydrop');
var selectBoxContainer = $('<div>', {
width: select.outerWidth(),
className: 'tzSelect',
html: '<div class="selectBox"></div>'
});
var dropDown = $('<ul>', {className: 'dropDown'});
var selectBox = selectBoxContainer.find('.selectBox');
// Looping though the options of the original select element
select.find('option').each(function (i) {
var option = $(this);
if (i == select.attr('selectedIndex')) {
selectBox.html(option.text());
}
// As of jQuery 1.4.3 we can access HTML5
// data attributes with the data() method.
if (option.data('skip')) {
return true;
}
// Creating a dropdown item according to the
// data-icon and data-html-text HTML5 attributes:
var li = $('<li>', {
html: '<img src="' + option.data('icon') + '" /><span>' +
option.data('html-text') + '</span>'
});
li.click(function () {
selectBox.html(option.text());
dropDown.trigger('hide');
// When a click occurs, we are also reflecting
// the change on the original select element:
select.val(option.val());
return false;
});
dropDown.append(li);
});
selectBoxContainer.append(dropDown.hide());
select.hide().after(selectBoxContainer);
// Binding custom show and hide events on the dropDown:
dropDown.bind('show', function () {
if (dropDown.is(':animated')) {
return false;
}
selectBox.addClass('expanded');
dropDown.slideDown();
}).bind('hide', function () {
if (dropDown.is(':animated')) {
return false;
}
selectBox.removeClass('expanded');
dropDown.slideUp();
}).bind('toggle', function () {
if (selectBox.hasClass('expanded')) {
dropDown.trigger('hide');
}
else dropDown.trigger('show');
});
selectBox.click(function () {
dropDown.trigger('toggle');
return false;
});
// If we click anywhere on the page, while the
// dropdown is shown, it is going to be hidden:
$(document).click(function () {
dropDown.trigger('hide');
});
});
$(document).ready(function () {
$("#drop1").click(function () {
});
});
As mentioned in comments, your HTML is completelly changed, by jQuery script you use. Btw, it is very old script, and seems compatible just with older versions of jQuery.... However, instead <select> element which is removed, now you have <ul> with .dropDown class. To get selected value, you can do something like this:
$(".dropDown li").click(function () {
console.log($(this).text())
});
Demo:
$(document).ready(function () {
// The select element to be replaced:
var select = $('select.makeMeFancy');
var selectBoxContainer = $('<div>', {
width: select.outerWidth(),
className: 'tzSelect',
html: '<div class="selectBox"></div>'
});
var dropDown = $('<ul>', {className: 'dropDown'});
var selectBox = selectBoxContainer.find('.selectBox');
// Looping though the options of the original select element
select.find('option').each(function (i) {
var option = $(this);
if (i == select.attr('selectedIndex')) {
selectBox.html(option.text());
}
// As of jQuery 1.4.3 we can access HTML5
// data attributes with the data() method.
if (option.data('skip')) {
return true;
}
// Creating a dropdown item according to the
// data-icon and data-html-text HTML5 attributes:
var li = $('<li>', {
html: '<img src="' + option.data('icon') + '" /><span>' +
option.data('html-text') + '</span>'
});
li.click(function () {
selectBox.html(option.text());
dropDown.trigger('hide');
// When a click occurs, we are also reflecting
// the change on the original select element:
select.val(option.val());
return false;
});
dropDown.append(li);
});
selectBoxContainer.append(dropDown.hide());
select.hide().after(selectBoxContainer);
// Binding custom show and hide events on the dropDown:
dropDown.bind('show', function () {
if (dropDown.is(':animated')) {
return false;
}
selectBox.addClass('expanded');
dropDown.slideDown();
}).bind('hide', function () {
if (dropDown.is(':animated')) {
return false;
}
selectBox.removeClass('expanded');
dropDown.slideUp();
}).bind('toggle', function () {
if (selectBox.hasClass('expanded')) {
dropDown.trigger('hide');
}
else dropDown.trigger('show');
});
selectBox.click(function () {
dropDown.trigger('toggle');
return false;
});
// If we click anywhere on the page, while the
// dropdown is shown, it is going to be hidden:
$(document).click(function () {
dropDown.trigger('hide');
});
});
$(document).ready(function () {
$(".dropDown li").click(function () {
console.log($(this).text())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<select name="fancySelect" onchange="test()" class="makeMeFancy" id="drop1">
<option value="0" selected="selected" data-skip="1" data-icon="assets/images/large/bitcoin.png" data-html-text="BTC<i&gt">BTC<span class="select_coin_button_arrow">▾</span></option>
<option value="1" data-icon="assets/images/small/bitcoin.png" data-html-text="BTC<i&gt" >BTC</option>
<option value="17" data-icon="assets/images/small/ether.png" data-html-text="ETH<i>">ETH</option>
</select>

how to make the jquery function load before one ajax function finish

How do I fire one event before the previous function completed its function?
I have the following AJAX code :
var BrainyFilter = {
//...
init: function (opts) {},
changeTotalNumbers: function (data) {
jQuery(BrainyFilter.filterFormId).find('.bf-count').remove();
jQuery(BrainyFilter.filterFormId).find('option span').remove();
jQuery(BrainyFilter.filterFormId).find('select').removeAttr('disabled');
jQuery('.bf-attr-filter').not('#bf-price-container').find('input, option')
.attr('disabled', 'disabled')
.parents('.bf-attr-filter')
.addClass('bf-disabled');
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
jQuery('.bf-attr-' + data[i].id + ' .bf-attr-val').each(function (ii, v) {
if (jQuery(v).text() == data[i].val) {
var parent = jQuery(v).parents('.bf-attr-filter').eq(0);
var isOption = jQuery(v).prop('tagName') == 'OPTION';
var selected = false;
if (isOption) {
jQuery(v).removeAttr('disabled');
selected = jQuery(v)[0].selected;
} else {
parent.find('input').removeAttr('disabled');
selected = parent.find('input')[0].checked;
}
parent.removeClass('bf-disabled');
if (!selected) {
if (!isOption) {
parent.find('.bf-cell').last().append('<span class="bf-count">' + data[i].c + '</span>');
} else {
jQuery(v).append('<span> (' + data[i].c + ')</span>');
}
}
}
});
}
jQuery('.bf-attr-filter input[type=checkbox]').filter(':checked')
.parents('.bf-attr-block').find('.bf-count').each(function (i, v) {
var t = '+' + jQuery(v).text();
jQuery(v).text(t);
});
// since opencart standard filters use logical OR, all the filter groups
// should have '+' if any filter was selected
if (jQuery('.bf-opencart-filters input[type=checkbox]:checked').size()) {
jQuery('.bf-opencart-filters .bf-count').each(function (i, v) {
var t = '+' + jQuery(v).text().replace('+', '');
jQuery(v).text(t);
});
}
}
// disable select box if it hasn't any active option
jQuery(BrainyFilter.filterFormId).find('select').each(function (i, v) {
if (jQuery(v).find('option').not('.bf-default,[disabled]').size() == 0) {
jQuery(v).attr('disabled', 'true');
}
});
},
//...
} // close the BrainyFilter
I also have another jQuery file running to get the bf-count value using $('.bf-count').text().
When the page load, the bf-count value is empty. Since the code above inject the bf-count, I will need to wait until it finishes the for loop in order to get the bf-count value.
What is the best way to approach this?
without knowing how the second js file is loaded, I can only give you a guesstimate suggestion.
If you want to run the second js file code after the page is fully loaded, you can wrap the code in:
jQuery(window).load(function(){
//your code here. runs after the page is fully loaded
});
jQuery documentation: http://api.jquery.com/load-event/
"The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object."

First click is not working in jquery

I am trying to make a seatchart. All seats are elements. I click first seat and after that i click the other one. Second one changed its colour but first one is not working. Why?
function seatObject(id, label, status, token){
this.id = id;
this.label = label;
this.status = status;
this.token = token;
}
var seats = [];
var currentSeat;
function initAll() {
$(".seatObj").each(function() {
var id = $(this).attr("id");
var temp = new seatObject("#" + id, "label" + id, "available", "");
seats[id] = temp;
$("#" + id).click(function () {
currentSeat = $(this).attr("id");
if (seats[currentSeat].status == "selected")
{
dequeueSeat();
}
else
{
enqueueSeat();
//alert($(this).attr("inkscape:label"));
}
});
});
}
No problem with your code dude...
You need little changes...
Ordinary Click does not attach an event handler functions for one or more events. So use on method - Attach an event handler function for one or more events to the selected elements.
$(".seatObj").on('click',"#" + id, function () {
currentSeat = $(this).attr("id");
if (seats[currentSeat].status == "selected")
{
dequeueSeat();
}
else
{
enqueueSeat();
//alert($(this).attr("inkscape:label"));
}
});
You can use class instead of id in on method.
Try wrapping the function in $( document ).ready(function() {}
works for me.

jQuery Function - return a value with two clicks

I want to carry a value inside a JavaScript function but use jQuery to detect the click or hover state.
function foo(bar){
var choc=bar;
}
When I click foo() I want it detect the first click and the second so I can do an image swap.
Example:
function foo(bar) {
var choc=id;
$(id).click(function () {
alert('first click');
}, function () {
alert('second click');
});
}
I can only return first click. This is what I am trying to do:
An example which will not work
open <img id="5" class="swap5" src="down.png" />
<div id="box5">press the up button to close me</div>
jQuery
$(document).ready(function() {
$(".open").click(function(event){
var id = event.target.id;
$('#box' + id).slideToggle();
$(".swap"+id).attr("src", "up.png");
}, function () {
var id = event.target.id;
$('#box' + id).slideToggle();
$(".swap"+id).attr("src", "down.png");
});
});
Use .toggle instead of .click.
$(document).ready(function() {
$(".open").toggle(function(event){
event.preventDefault();
var id = event.target.id;
$('#box' + id).slideToggle();
$(".swap"+id).attr("src", "up.png");
}, function (event) {
event.preventDefault();
var id = event.target.id;
$('#box' + id).slideToggle();
$(".swap"+id).attr("src", "down.png");
});
});
Also lose the href="javascript:open(5);" in the <a> tag. Use href="#" instead.
This is a pretty hacky solution, but here is my take at it.
Declare a counter variable that is initialized at 0.
On click increment it and do a check to see if it is 2 to perform your action.
var counter = 0;
function foo(bar) {
var choc=id;
$(id).click(function () {
if(counter == 2) {
//Perform action
counter = 0; //reset counter
} else {
counter++; //Increment counter
}
});
}
Did you try using the double click event handler? Check out a description by going to: http://api.jquery.com/dblclick/
It's pretty well documented so you should find it straight forward to implement

Is there a way to convert this jquery code to javascript?

I'm trying to create a tab menu. And I need this coded in regular javascript, not jquery.
$(document).ready(function() {
//When page loads...
$(".general_info_content").hide(); //Hide all content
$("ul.general_info_tabs li:first").addClass("active").show(); //Activate first tab
$(".general_info_content:first").show(); //Show first tab content
//On Click Event
$("ul.general_info_tabs li").click(function() {
$("ul.general_info_tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".general_info_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
The core of what you want to do is below - I'm sure there are a thousand different ways to do each task:
Remove a CSS class from an element:
var classes = document.getElementById([id]).className.split(" ");
for(var i = 0; i < classes.length; i++)
if(classes[i] == removeClass)
classes[i] = "";
document.getElementById([id]).className = classes.join(" ");
Add a CSS class to an element:
document.getElementById([i]).className += " " + addClassName;
Hide an element:
document.getElementById([i]).style.display = "none";
Fade an element:
// not tested, but based on tested/used code
function fade(el, opacity, fadeInTime) {
if (opacity < 100) {
el.style.opacity = opacity / 100;
el.style.filter = "alpha(opacity=" + opacity + ")";
opacity += 5;
setTimeout(function () { fade(el, opacity, fadeInTime); }, fadeInTime / 5);
}
}
To find all elements by CSS and tag name:
var matches = new Array();
var all = document.getElementByTagName(searchTagName);
for(var i = 0; i < all.length; i++){
if(all[i].className.replace(searchClassName, "") != all[i].className) {
matches.push(all[i].className);
}
}
// do something with (i.e., return or process) matches
And for the record, I find it encouraging, not unreasonable, that a person using the jQuery library wants to know how to do get things done with native JS/DOM.
More functions to complement Brian's post. Good luck.
EDIT: As I mentioned I would change the class=general_info_content to id=general_info_content1.
function attach(el, event, fnc) {
//attach event to the element
if (el.addEventListener) {
el.addEventListener(event, fnc, false);
}
else if (document.attachEvent) {
el["on" + event] = fnc; // Don not use attachEvent as it breaks 'this'
}
}
function ready() {
// put all your code within $(function(){}); here.
}
function init() {
attach(document, "readystatechange", function () {
if (document.readyState == "complete") {
ready();
}
});
}

Categories

Resources