I have a single page with a div that gets new content when a user click on a radio button, when the page is loaded it display the main content, when user click on X radio button, that content gets "re-new" or "different" information, there is a DIV id that doesn't change... so...
When user loads the page, I check fro some values, is X value is lower than then replace the div content, on the first load it works fine, but if the user changes options then the first script wont do nothing... so here is the basic html
<div id="options">
<input type="radio" onclick="javascript:checkOut(this.name,'shipr');" value="1" name="shipping" id="s1">
<input type="radio" onclick="javascript:checkOut(this.name,'shipr');" value="2" name="shipping" id="s2">
<input type="text" id="qty" class="hidden" value="1.2" style="display: none;">
</div>
<div id="information">
<div id="prices>$120.00</div>
<div id="products">Multiple[...] and tabs long list</div>
<div id="checkoutbtn">Buy Now</div>
</div>
Basically when user click on any of the radio buttons the content of the div "information" gets replace by ajax information, I'd like to know how do I get the new content and "replace" some values...
Now, the input with the ID qty that is hidden has the value I need is that value is less or grater than I replace the button inside the div with the id checkoutbtn from "buy now" to "Only inside US and UK, please Request a quote"... so, my JS is:
(function($) {
var pkg = $("#qty").val();
var cot = '<a rel="{handler: \'iframe\', size: {x: 570, y: 550}}" ' +
'class="modal" href="qut.php">' +
'<input type="button" value="Quotation" class="btn btn-small">' +
'</a>';
window.onload = function() {
if (pkg < 4 ) {
// do something
// alert('Checked');
$('#checkoutbtn').html(cot);
}
};
$('input:radio[name="shipping"]').change(
function(){
if ($(this).is(':checked') && $(this).attr("id") == 's1') {
// alert(pkg);
$('#checkoutbtn').html(cot);
} else if ($(this).is(':checked') && $(this).attr("id") == 's2') {
$('#checkoutbtn').html(cot);
}
});
})(jQuery);
When the page is load for the first time it works fine, and if it wasn't for the ajax that change the content of the div with the id information it would be flawless, but is not...
As you can see I have this piece of code: $('input:radio[name="shipping"]').change() ... so now I need something that would give some time to load the new content or to check when the new content is ready and then execute this other code $('#checkoutbtn').html(cot); ... the question is, how do I do that... if I put a timeout of 2 seconds it might work, but sometimes it takes 3 or 5 seconds for the new information to be ready and available to the user and that would be a problem...
So, I need to check when the new content is ready after the user has click on the radio button, how do I do that?
Thank you.
Related
I have a web page with a bunch of automatically generated contents (I can't touch the HTML). Usually, what happens is:
User selects something on the web page (ex. enter donation amount)
User clicks a button to enter personal information (as far as I know, the inputs are loaded after the button is clicked and takes around 1-2 seconds to load)
I'm trying to add some code to allow the user to enter some information before clicking the button, and the logic basically works like this:
the web page is loaded
place mydiv between some automatically generated contents
when user selects an option, put that information in local storage
when user clicks the button to generate personal informations, use setinterval to try to put the value in local storage in the corresponding field every 100ms, and call clearInterval when it succeeds (basically, it should work with 100ms of the personal information fields being loaded)
<style>
/* some styles */
</style>
<div id="mydiv">
<span style="font-weight:bold; margin-left: 12px;">
Please select an option
</span>
<div id="mydiv-options" style="margin-left: 14px;">
<input id="getinfo-mydiv" type="radio" name="mydiv-question" onclick="setstorage(0)">
</input>
<label for="getinfo-mydiv">
option1
</label>
<br>
<input id="future-mydiv" type="radio" name="mydiv-question" onclick="setstorage(1)">
</input>
<label for="future-mydiv">
option2
</label>
<br>
<input id="already-mydiv" type="radio" name="mydiv-question" onclick="setstorage(2)">
</input>
<label for="already-mydiv">
option3
</label>
<br>
<div id="clear-selection" onClick="clearSelection()">
Clear selection
</div>
</div>
</div>
<script>
// some functions
let repeatTryCheck = null
function setstorage(x) {
console.log("setstorage")
window.localStorage.setItem('selected', x)
}
function tryClickInput() {
console.log('tryClickInput')
let elementLoadedAfterUserClicksButton = document.getElementById("some-input")
if (elementLoadedAfterUserClicksButton == null) {
return
} else {
clearInterval(repeatTryCheck)
}
// do stuff with the value from storage
}
function tryClickUntilLoaded() {
console.log("tryClickUntilLoaded")
repeatTryCheck = setInterval(tryClickInput, 100) // 10x per second
}
function placeBeforeGeneratedDiv() {
console.log("placeBeforeGeneratedDiv")
let comments = document.getElementById("generateddiv")
comments.insertAdjacentElement('beforebegin', document.getElementById("mydiv"))
document.getElementById("mydiv").style.display = "block"
}
var i = 0;
function init() {
console.log("init")
placeBeforeGeneratedDiv() // place mydiv before generateddiv
document.getElementById('button-to-load-personal-info').addEventListener('click', tryClickUntilLoaded)
setstorage(null)
console.log(i)
i = i + 1
}
window.onload = init
</script>
The problem I keep getting is that the init function keeps getting called and I can't figure out what's causing it (I used this code on another page and it worked well)
Thanks
I am creating an admin panel and I have a panel on the left side of my page that I want to bring up different data.
I created a JSFiddle to show what I am doing.
The issue I am having is I want the dashboard home message...
<div id="dashboard_home">Welcome to the Admin Dashboard</div>
To be the only div that shows up on page load. Then when a panel seletion is clicked on, for the dashboard home message to go away and then only that new panel selection's div to show up.
Then once another panel selection is clicked on, I want the previous selection to hide and the new one to display and so fourth for all of the selections.
What do I need to do?
HTML
<div class="panel_out">
<div class="panel">
<input type='button' class="panel_buttons" id='user_request_button' value='User Requests'>
<input type='button' class="panel_buttons" id='message_button' value='Message Center'>
<input type='button' class="panel_buttons" id='draft_order_button' value='Draft Order'>
<input type='button' class="panel_buttons" id='draft_input_button' value='Draft Input'>
<input type='button' class="panel_buttons" id='announcements_button' value='Announcements'>
<input type='button' class="panel_buttons" id='dues_button' value='League Dues'>
</div>
</div>
<div class="dashboard_selection">
<div id='user_requests'>User Requests</div>
<div id='message_center'>Message Center</div>
<div id='draft_order'>Draft Order</div>
<div id='draft_input'>Draft Input</div>
<div id='announcements'>Announcements</div>
<div id='dues'>Leauge Dues</div>
</div>
JS
jQuery(document).ready(function () {
jQuery('#user_request_button').on('click', function (event) {
jQuery('#user_requests').toggle('hide');
});
jQuery('#message_button').on('click', function (event) {
jQuery('#message_center').toggle('hide');
});
jQuery('#draft_order_button').on('click', function (event) {
jQuery('#draft_order').toggle('hide');
});
jQuery('#draft_input_button').on('click', function (event) {
jQuery('#draft_input').toggle('show');
});
jQuery('#announcements_button').on('click', function (event) {
jQuery('#announcements').toggle('show');
});
jQuery('#dues_button').on('click', function (event) {
jQuery('#dues').toggle('show');
});
});
Demo
You're adding far too many bespoke events when you don't need to. Normalise your IDs to match the button IDs and derive one from the other,
e.g. <input id='user_requests_button' /> finds <div id="user_requests">
Show the div you want, then use siblings() to get the elements that you want hidden, and hide them.
Trigger the click event on the first button on load to show the first one only when the page loads (if you don't do this with CSS).
jQuery(document).ready(function () {
$('.panel_out input').on('click', function(){
// derive the ID
var id_to_show = '#' + this.id.replace('_button', '');
// show one and hide the others
$(id_to_show).show().siblings().hide();
}).first().trigger('click'); // trigger the first on page load
});
Trigger the click event on the first button on load to show the first one only when the page loads (if you don't do this with CSS).
On a click hide all panels first. And then open the desired one with .show()
So i would do it this way:
$('.panel').click(function(e){
$('.panel').hide();
$(e.currentTarget).closest('panel').show();
});
I am having a problem figuring out the correct way to do the following: Add a new form to my div when a button, 'add_skill', is clicked, disable the button to add a new form to my div,. Then when the person clicks the new button within the new form, 'button123', the form would submit the data through AJAX, and then remove the form, and re-enable the button, 'add_skill' so that another form could be added.
So far, I've been able to add the form to the bottom of the div. But when I click the 'button123' button in the new form, jQuery doesn't seem to recognize it, and no jQuery actions are done.
Am I even going about this the right way? I'm essentially trying to make something so you can keep adding new data to a bottom of a div, one after another, by clicking a '+' button. Think of adding items to a resume, one after another. That's is what I have in mind.
Here's my JS.
//dynamic add new skill form
var i = 0;
$(".add_skill").click(function(){
//inputs for Skill and Percentage
var skill = "<div class='new_skill_input' id='num" + i + "'> \
<label class='control-label'>Skill:</label> \
<input type='text' placeholder='SFML' class='ctrl-textbox'> \
<input type='hidden' class='hiddenObligatoire' value='false'> \
</div> \
<div class='new_skill_input'> \
<label class='control-label'>Percentage:</label> \
<input type='text' placeholder='85' class='ctrl-textbox'> \
<input type='hidden' class='hiddenObligatoire' value='false'> \
</div>\
<div class='new_skill_input'>\
<input class='button123' type='submit' value='Add'>\
</div>";
$(skill).appendTo(".skills"); //add form items to end of div
i++; //increment for identity
$(".add_skill").prop("disabled", true); //disable (add form), only 1 at a time
});
$(function() {
$("button123").click( function()
{
$(".add_skill").prop("disabled", false); //re-enable (add form)
}
);
});
And here is my HTML:
<div class="timeline-panel skills">
<h1>Skills</h1>
<div class="hr-left"></div>
<!--Add new skill start-->
<div class="new_skill">
<input class="btn add_skill" style="font-family:Helvetica" style="float:left;" type="submit" value="+">
</div>
<!--add new skill end-->
</div>
Any tips would be greatly appreciated. Thank you in advance.
This is a great use-case for event delegation:
Change:
$("button123").click(<handler>)
...to:
$(document).on('click', '.button123', <handler>);
Also, note that the selector should be .button123 with the '.' in front.
extending #jmar777's answer instead of $(document).on('click', '.button123', <handler>); one can use $(parent).on('click', '.button123', <handler>); where parent is button123's parent element which is present in DOM, as event doesn't need to bubble till document. event bubbling explained here
This is my HTML code. I am using Jasny bootstrap for image upload, and Bootstrap-Switch do get the iOS style switch box.
By default, I want to:
Disable every element in Div #one except the very first switch box. (It is in the indeterminate state to start with)
When the user flicks that first element to either on or off, the next input field becomes enabled.
And so on.
Basically, I want the user to have to fill out the form in order.
Not all of the fields are check boxes. As you can see from this example, there is an image upload form which I want to work in the same way - disabled until the field before it has been completed, and then enabled. And once the image has been uploaded, then enable the next input field, and so on.
Is there any jQuery magic I can use to easily do this?
<div id="one">
<!-- Bootstrap switch box -->
<div class="s-part-question">
<label>X</label>
<div>
<input name="X1" type="checkbox" class="s-switch-indeterminate s-t-input"
data-indeterminate="true"
data-on-text="Yes"
data-off-text="No" />
</div>
</div>
<!-- Bootstrap switch box -->
<div class="s-part-question">
<label>Y</label>
<div>
<input name="Y1" type="checkbox" class="s-switch-indeterminate s-t-input"
data-indeterminate="true"
data-on-text="Yes"
data-off-text="No" />
</div>
</div>
<!-- Image upload -->
<div class="fileinput fileinput-new s-part-photo" data-provides="fileinput">
<div class="s-part-photo-explain">Add image</div>
<div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-default btn-file">
<span class="fileinput-new">New</span>
<span class="fileinput-exists">Change</span>
<input class="s-t-input" type="file" name="imageY1">
</span>
Remove
</div>
</div>
<!-- Bootstrap switch box -->
<div class="s-part-question">
<label>Z1</label>
<div>
<input name="Z1" type="checkbox" class="s-switch-indeterminate s-t-input"
data-indeterminate="true"
data-on-text="Yes"
data-off-text="No" />
</div>
</div>
</div>
$(".s-switch-indeterminate").bootstrapSwitch({
'state': null
});
I did something similar, but the way I did it was to dynamically include the HTML after every section. So I would start in the HTML with:
<div id="one">
<div id="first">
<!-- Bootstrap switch box -->
<div class="s-part-question">
<label>X</label>
<div>
<input name="X1" type="checkbox" class="s-switch-indeterminate s-t-input"
data-indeterminate="true"
data-on-text="Yes"
data-off-text="No" />
</div>
</div>
</div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
etc.
where I've added a div section for each checkbox with its own unique ID (first, second, third etc).
Then when the checkbox has changed, you can check it with jQuery and insert the next sections HTML with Javascript.
$("input[name='X1']").change(function() {
document.getElementById("second").innerHTML = '<div class="s-part-question"><label>Y</label><div><input name="Y1" type="checkbox" class="s-switch-indeterminate s-t-input" data-indeterminate="true" data-on-text="Yes" data-off-text="No" /></div></div>'
}
Then have one of these for each checkbox. Also note for the dynamically generated checkbox, you will have to have to make a change to the jQuery selector to so:
$('#one').on("input[name='Y1']", "change", function() {
If I understand you correctly, you want the following:
(1) Every DIV element is disabled, except the first one.
(2) When the user checks the checkbox in the first DIV on or off (to checked or not checked), then the second checkbox becomes enabled. This second checkbox stays enabled even when the user change the first checkbox back to what it was.
(3) Then when the second checkbox is checked (or unchecked if already checked), the next input becomes enabled.
(4) And so on...
If so, the next codes should help:
$(document).ready(function(){
var nodeList = document.querySelectorAll("div#one > div");//Selects all DIRECT child elements specified by “child” of elements specified by “parent”. In this case it takes the parent DIV of the switch boxes and all its children (and inner html) "only one level down".
//http://api.jquery.com/category/selectors/
var amountInputs = new Array();
for(i=0;i<nodeList.length;i++){
//In each Bootstrap switch box
var inputFields = nodeList[i].querySelectorAll("input");
amountInputs[i] = inputFields.length;
if( i==0 ){
putOnSurveillance(inputFields);
} else{
for(j=0;j<amountInputs[i];j++){
$( inputFields[j] ).attr('disabled','disabled');
}
}
}
jObjects['amountInputs'] = amountInputs;
});
var jObjects = { /* JavaScipt Objects */
current_SwitchBox: 0,//Current switch box index number
surveillancePassed: 0
};
function enableNextSwitchBox(){
var nodeList = document.querySelectorAll("div#one > div");
if( jObjects['current_SwitchBox']!=nodeList.length ){
var inputFields = nodeList[jObjects['current_SwitchBox']].querySelectorAll("input");
for(l=0;l<inputFields.length;l++)
$( inputFields[l] ).prop("disabled", false);
putOnSurveillance(inputFields);
} else{
//No more Switch Boxes to enable!!!
}
}
function putOnSurveillance(inputs){
for(k=0;k<inputs.length;k++){
$( inputs[k] ).change( {targetInput: inputs[k]}, function(object) {
$( object.data.targetInput ).unbind('change');//You are not under "surveillance" anymore...
if( jObjects['amountInputs'][jObjects['current_SwitchBox']]==(++jObjects['surveillancePassed']) ){
++jObjects['current_SwitchBox'];
jObjects['surveillancePassed'] = 0;
enableNextSwitchBox();
}
});
}
}
Explanation:
1)Variable " nodeList " is the DIV which contains all the Bootstrap switch boxes
2)Variable " nodeList[] " -> in each nodeList[i] (i-> 0,1,2,3....) contains a Bootstrap switch box
3)Next: at each nodeList[i], we will searches for any input tags (or elements). If there is more than one input fields in that switch box, it will automatically detect them.
4)Disable all input fields, but the input fields in the "FIRST" Bootstrap switch box.
!This only works with "input" tags!
5)An amount of <input> per Bootstrap switch box will be saved as JavaScript Object for use later
6)The <input>'s of the first Switch Box (which are not disabled), are put on "surveillance". If its value is changed, that same input won't be on "surveillance" anymore, and then by using a javascript object (variable), it will check if all other <input>'s in that same Switch Box has already changed before.
If so, then all <input>'s on the next Bootstrap Switch Box becomes enabled.
7)The <input>'s on the next switch box are enabled and so on....
Bonus: This code should work with any type of input + any amount of input you have in that particular Bootstrap switch box + any amount of Bootstrap switch boxes you have!!!
i have a page that show activity feeds with a comment link for each feed, i add a comment form dynamically like this :
$("#feedList").on("click", ".comment-link", function(e){
$(this).parent().append('<form method="post" action="#" class="commentForm"><p><textarea class="comment"></textarea></p><p><input type="submit" value="add" class="send-Comment-Btn" /></p></form>');
$("textarea.comment").select();
return false;
});
when i scroll down my page and i click in some comment link it shows me the form as expected, but if i scroll to the top of the page again and i try to click a comment link it shows the form too but it scroll me to the bottom page to the last link i have clicked before, someone can tell me why this behavior and solution for this ?
$("textarea.comment").select();
will always move you to first created textarea element with class "comment". Maybe you must add some ID that increments every click like:
var someID = 0;
$("#feedList").on("click", ".comment-link", function(e){
someID += 1;
$(this).parent().append('<form method="post" action="#" class="commentForm"><p><textarea class="comment" id="selectorForComment' + someID + '"></textarea></p><p><input type="submit" value="add" class="send-Comment-Btn" /></p></form>');
$("#selectorForComment" + someID).select();
return false;
});