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
Related
I'm trying to have a display that shows something of a RAG status when certain checkboxes are clicked, example:
if no boxes are checked, show image 1 (grey)
if the first box is checked, show image 2 (red)
if both boxes are checked, show image 3 (green)
This is meant to show that a system is not impacted (grey), whether it is offline (red) or was offline but has now recovered (green).
I have an html checkbox and an html image with ID tags, as well as all 3 images uploaded to the site I'll be adding this into, with the following code script embedded in the html. Once this is working, can someone advise how to make the grey icon show again once the boxes are unchecked, that would be great - will the If statements work on uncheck, as it's an on-click event?
Javascript:
function customerImpact();
var customerImpactIcon = documet.getElementById("customerImpactIcon");
var customerImpact = document.getElementById("customerImpact");
var customerImpactCleared = document.getElementById("customerImpactCleared");
if (customerImpact == true){
if (customerImpactCleared == true){
customerImpactIcon.src="image3.jpg"
}
else {
customerImpactIcon.src="image2.jpg"
}
}
else {
customerImpactIcon.src="image1.jpg"
}
}
HTML:
<img src="image1.jpg" id="customerImpactIcon" alt="customerImpact" width="70" height="118" />
<input type="checkbox" id="customerImpact" onclick="customerImpact()">
<input type="checkbox" id="customerImpactCleared">
If you are allowed to change your HTML a little, you don't need Javascript at all. Using CSS would be sufficient.
#status {
width: 100px;
height: 100px;
background-image: url("https://via.placeholder.com/100/33333");
}
#customerImpact:checked+#customerImpactCleared:not(:checked)+#status {
background-image: url("https://via.placeholder.com/100/FF0000");
}
#customerImpact:checked+#customerImpactCleared:checked+#status {
background-image: url("https://via.placeholder.com/100/008000");
}
<input type="checkbox" id="customerImpact">
<input type="checkbox" id="customerImpactCleared">
<div id="status"></div>
Currently you are querying for the checkbox HTMLElements and checking for their truthiness (customerImpact == true). They will always be truthy regardless of whether they are checked or not. You want to check if the checked property on the checkboxes is true.
I made a small example (without images, but it should be easy for you adapt it). I also opted to use the change event instead of the click event.
const status = document.querySelector('[data-status]');
function update() {
const customerImpact = document.querySelector('[data-customer-impact]').checked;
const customerImpactCleared = document.querySelector('[data-customer-impact-cleared]').checked;
if (customerImpact && customerImpactCleared) {
status.textContent = 'Recovered';
} else if (customerImpact) {
status.textContent = 'Offline';
} else {
status.textContent = 'No impact';
}
}
update();
<p data-status></p>
<input id="customer-impact" type="checkbox" data-customer-impact onchange="update()">
<label for="customer-impact">Customer Impact</label><br>
<input id="customer-impact-cleared" type="checkbox" data-customer-impact-cleared onchange="update()">
<label for="customer-impact-cleared">Customer Impact Cleared</label>
I have POS system with cheque payments. when the cashier input the number of cheque according to the input the cheque detail form should generated.
Eg : if he enter Number 5, the same form should be display five times How can i do this with jquery.
I have attached up to what i have done so far !!
Thanks in Advance
This is the user input
<input type="number" class="form-control" id="numberOfChq" >
<a id="come" class="btn btn-primary">Submit</a>
This is the div to be repeated
<div id="chk_list" hidden></div>
This is the jquery i tried its displaying only once, i want to diplay as many user input
$("#come").click(function(){
var chqNumebr = $("#numberOfChq").val();
var i;
for (i= 1; i <= chqNumebr; i++ ){
var chqSh = $("#chk_list").slideDown("slow");
}
});
Try the below.
First we need something to add the new divs into, so I created <div id="output"></div> for that.
After pressing submit, you'll see the new divs get added according the number the user entered. But we have to make sure that we empty #output every time the function runs otherwise the newly created divs would just keep adding onto the existing ones.
Secondly, if we are going to have multiple instances of #chk_list then it shouldn't have an ID as all ID's should be unique. Instead, we'll use a class.
$("#come").on('click', function() {
var chqNumebr = $("#numberOfChq").val();
//empty divs that are currently inside of #output
$('#output').empty();
for (var i = 0; i < chqNumebr; i++) {
$('#output').append('<div class="chk_list"></div>')
}
});
.chk_list {
width: 50px;
height: 30px;
background: red;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="form-control" id="numberOfChq">
<a id="come" class="btn btn-primary">Submit</a>
<div id="output"></div>
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.
Currently the users see login page when they open the application. Upon signing in, they get into the main page. I want to prevent the user from going back to the login page once they are logged in which the user can easily do by just clicking on the back button on the phone or the web browser.
The following method does that by preventing me from going back or forth to the page I want. For example if I identify the id as #home, it is going to prevent me from going back to homepage. Problem is this works for all my pages in my application less the one page I actually want to enforce this on which is my login page. When I use the login page's id, nothing happens and I am able to go back to the login page by clicking the back button. Please advise what I am doing wrong.
JS
// triggers when leaving any page
//this doesn't work cos I am using the id of my loginpage. Other page's ids works.
$(document).on('pagebeforechange', function (e, data) {
var to = data.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#loginForm') { //will work if I use #benefits for example.
alert('Can not transition the page!');
$.mobile.changePage("#home", {
transition: "flip"
});
e.preventDefault();
e.stopPropagation();
// remove active status on a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-shadow').css({
'box-shadow': '0 0 0 #3388CC'
});
}
}
});
HTML for LOG IN Page
<div data-role="page" id="loginForm" data-theme="e" data-add-back-btn="false">
<header data-role="header">
<h1>Log In</h1>
</header>
<form id="form1" name="form1" method="GET" action="http://example.com">
<label for="id">Username </label>
<input type="text" name="id" id="id" />
<label for="password">Password </label>
<input type="password" name="password" id="password" />
<input type="hidden" name="rank" id="rank" value="123">
<input type="submit" name="submit" value="Login"/>
</form>
</div>
HTML for Benefits Page
<div data-role="page" id="benefits" data-theme="e">
<header data-role="header">
<h1>Benefits</h1>
</header>
<article data-role="content" >
<div data-role="collapsible-set" id="benefitsList">
<!--will fill up with info from database-->
</div>
</article>
</div>
EDITED:
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = $.mobile.pageContainer.pagecontainer("getActivePage");
$.mobile.pageContainer.pagecontainer("change", current);
}
}
});
The problem that the code above works on all pages except for first page loaded, is because - by default - jQM doesn't change hash in URL for first page. The code above checks if there retrieves hash from URL, since there is no hash for first page, it returns false and thus doesn't prevent user from going back to "login page".
The code below checks URL and compares it with .url of first page loaded. The .url is stored in $.mobile.navigate.history.stack and it has 0 index, since it is first page.
jQuery Mobile 1.4
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = "#" + $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
window.location.hash += current;
return false; /* this will stop page change process */
}
}
});
jQuery Mobile <= 1.3
Change
$.mobile.navigate.history.stack[0].url
to
$.mobile.urlHistory.stack[0].url
Change
$.mobile.pageContainer.pagecontainer("getActivePage")[0].id
to
$.mobile.activePage[0].id
Demo - Code
I'm trying to create a very basic bookmarklet.
My form exists on page, for example mysite.com/posts/, within a bootstrap modal box.
<div class="post-window">
<div class="window-left">
<textarea name="title_image" class="form-control" rows="3" placeholder="Post title"></textarea>
<input name="postimage" class="form-control" placeholder="Post image URL" />
</div>
</div>
<div class="modal-bottom">
<div class="upload">
<input type="hidden" name="letsbingo" value="1" />
<button class="btn-block">Post Selfie</button>
</div>
</div>
1- Following is bookmarklet code and it works fine.
javascript: var selfiesite = 'SelfieNow',
selfiesiteurl = 'http://my.com/post/';
(function () {
if (window.selfiesiteit !== undefined) {
selfiesiteit();
} else {
document.body.appendChild(document.createElement('script')).src = 'http://my.com/assets/js/postit.js';
}
})();
2- The result of above javascript is exactly what I want as shown below
http://my.com/post/?postimage=%3A%2F%2Fexample.com%2Fwp-content%2Fuploads%2F2013%2F12%2FGripster-Wrap-Mini-For-The-Ipad-Mini-3-690x460.jpg&title_image=Example%20-%20Men%27s%20Gear%2C%20Lifestyle%20and%20Trends
3- Now my my.com/post/ contians a piece of javascripts which triggers modal box on window load.
jQuery(window).load(function ($) {
jQuery('#postModal').modal('show');
});
The bookmarklet is working, modal box is opening on window load. But data in not passing to form. The form opens in modal box, url changed but the form appears empty. I don't know what is wrong. Either the modal box is opening (on window load) the wrong way or the bookmarklet created url isn't fit for this kind of form. Please guide me a little bit.
Try to bind your JS function when the modal is show. Like this:
$('#postModal').on('show', function () {
var selfiesite = 'SelfieNow',
selfiesiteurl = 'http://my.com/post/';
if (window.selfiesiteit !== undefined) {
selfiesiteit();
} else {
document.body.appendChild(document.createElement('script')).src = 'http://my.com/assets/js/postit.js';
}
});