I need to be able to set a counter to monitor how many errors have been generated when a form is submitted. Errors are highlighted by a css class .validmissing.
So if user has 5 errors on submit - counter is set to 1
If user resubmits the form and then gets 3 errors my counter needs increment to 2 in the same session.
<script type="text/javascript">
var ErrorCounter = 0;
$(document).ready(function() {
if($('.validmissing').length > 0) {
ErrorCounter = 1;
else{
ErrorCounter = 0;
}
});
</script>
Do i need to set a cookie or a session variable?
You can use the jQuery.cookie plugin
Its pretty simple to use.
To set a cookie:
$.cookie('cookieName', val, {path: "/", expires: 1})
To get a cookie, I think just:
$.cookie('cookieName');
There's an option to let the cookie last for a session as well instead of number of days as shown in the expires above.
you can use cookie or session variable that will work but better is use the input hidden filed where you have previous counter stored.
HTML
<form method="get">
<input type="hidden" value="" name="counter" id="counter" />
..........
..........
</form>
Javascript
<script type="text/javascript">
//http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return 0;
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var ErrorCounter = 0;
$(document).ready(function() {
$("#counter").val(getParameterByName("counter"));
if($('.validmissing').length > 0) {
ErrorCounter = $("#counter").val();
ErrorCounter = 1*ErrorCounter + 1;
$("#counter").val(ErrorCounter);
});
</script>
Related
I'm trying to make a simple website for a friend. The purpose is picking a ticket and showing an alert and disabling the button showing that the ticket has been already redeemed. I also want to store that on a cookie, because if my friend leaves the webpage, the values are restored to default and not based on the choices my friend have made.
The HTML code is this:
<img id="first_ticket" src="ticket_not_edited.png" width="50%">
<br>
<button id="first_button" class="ticket1" onclick="first()">Redeem</button>
The JavaScript code is:
function first() {
alert("You've redeemed successfuly the first ticket.");
document.getElementById("first_button").style.background='#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src='broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
The purpose is to store the user's choice on a cookie so I can always check what my friend has chosen to disable the ticket and the button availability.
Also, how can I make it to check if my friend chose a ticket to disable some options (by "some options" I'm referring to disabling the button and changing the image to a broken ticket"?
Thanks in advance!
You can use document. cookie to store the answer, and you can check in the link below to know if it exists.
Got it from here:
final:
<img id="first_ticket" src="" width="50%">
<br>
<button id="first_button" class="ticket1" onclick="checkIfExists()">Canjear</button>
<script>
// check if it Exists
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
var myCookie = getCookie("first");
if (myCookie == null) {
alert('Welcome! Please Choose A ticket below.');
}
else {
alert('Welcome back! You already choose a ticket!');
document.getElementById("first_button").style.background = '#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src = 'broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
function checkIfExists() {
if (myCookie == null) {
document.cookie = "first = 'yes'";
alert("You've redeemed successfuly the first ticket.");
document.getElementById("first_button").style.background = '#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src = 'broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
else {
alert('Oh. You already choose a ticket.');
}
}
</script>
This is my code
html input field
<input type="text" size = "3" name="couponadd" id="couponadd"
oninput="myFunction()" class="field" placeholder="Enter Coupon Code" />
Script Code
<script>
var lastval;
function myFunction() {
getting CouponDC,TicketypDC and CouponPrcDC from database
var CouponDC = $('#dbcoupan').val();
var TicketypDC = $('#dbtckettype').val();
var CouponPrcDC = $('#dbprice').val();
var total_price = $('#total_price').val();
Get getcoupon from input
var getcoupon = $("#couponadd").val(),
txt='Invaild Coupon';
check if user enter same coupon
if(getcoupon == lastval )
{
alert('You Cant Enter Same Code Again');
}
if coupon code match with database coupon
else if (getcoupon == CouponDC ) {
$amount=CouponPrcDC;
total_price = total_price * ((100-$amount) / 100);
minus some ammout from total if match
total_price = Math.round(total_price);
document.getElementById('Voucher_value').value = total_price;
}
if coupo don't match with database coupon
else if(getcoupon != CouponDC && getcoupon.length ==5 )
{
alert('WRONG COUPON CODE');
}
**store last value enter in input**
lastval = getcoupon;
$('#total_price').val(total_price);
}
</script>
You can store it in an array and check if it exists before moving ahead.
Pseudo code below:
var couponArr = [];
var getcoupon = $("#couponadd").val();
if($.inArray(getcoupon, couponArr) !== -1) {
alert('Coupon already used, can\'t use again.');
} else {
couponArr.push(getcoupon);
// your code here..
}
inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
Add a global tag variable and set default to false,use a if condition wrap the code need to run,then in the run code set it to true.
such as:
// in outer space
var hasCodeRun = false;
// in some function
if (!hasCodeRun) {
// run code here
hasCodeRun = true;
}
there are many questions similar to this but none of them seem to help with my situation.
I am developing a three step process using Javascript and html
I have 2 forms in the first two steps.each with a next/prev button
I need to be able to go back from step two back to step 1 and still have step ones form data in the fields. I am rather new to javascript any help would be appreciated. I am unsure how to save the form data and then insert it when the user goes back from step 2
EDIT:
I have decided to use JS to hide/show forms, please can someone tell me why my variable never gets to currentStep == 3; this causes issues when going back as it goes back to step one becasue the currentStep value is stuck at 2
var currentStep = 1;
function nextStep() {
if (currentStep ===1){
$("#petmain1").hide();
$("#petmain2").show();
$("#addproduct").show();
$("#firstimage").hide();
$("#secondimage").show();
currentStep = 2;
console.log("Current step is " + currentStep);
}else if(currentStep ===2){
$("#petmain2").hide();
$("#addproduct").hide();
$("#secondimage").hide();
$("#petmain3").show();
$("#thirdimage").show();
$("#firstimage").hide();
currentStep === 3;
console.log("Current step is " + currentStep);
}
}
function prevStep() {
if (currentStep ===2){
$("#petmain1").show();
$("#petmain2").hide();
$("#addproduct").hide();
$("#firstimage").show();
$("#secondimage").hide();
currentStep = 1;
console.log("Current step is " + currentStep);
}else if(currentStep === 3){
$("#petmain3").hide();
$("#thirdimage").hide();
$("#secondimage").show();
$("#petmain2").show();
$("#addproduct").show();
currentStep === 2;
console.log("Current step is " + currentStep);
}
}
You can use localStorage
On navigating from first step to second step you can store the value
if(typeof(Storage) !== "undefined") {
localStorage.setItem("someKey", $("#somField").val());
} else {
//
}
Again on navigating from second to first step check the local storage for the value and assign it to the fields in first form
$("#somField").val(localStorage.getItem("someKey"))
You may use sessionStorage.
HTML
<form>
Username : <input type='text' id='name'> <br />
Password : <input type='password' id='password'> <br />
<input type='button' onclick='storedata()' value='submit'>
</form>
<p id='res'></p>
JS
window.onload = function() {
if (sessionStorage.name && sessionStorage.password) {
document.getElementById("name").value = sessionStorage.name;
document.getElementById("password").value = sessionStorage.password;
}
};
function storedata() {
if(typeof(Storage) !== "undefined") {
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
sessionStorage.name = name;
sessionStorage.password = password;
document.getElementById("res").innerHTML = "Your datas restored";
} else {
document.getElementById("res").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Working Demo : https://jsfiddle.net/d83ohf6L/
Should be straightforward, but I just can't work out why this will not work! I'm a n00b, first off.
I have two input boxes that users need to fill in, a name and an amount. If these have been filled in, I change the query string on the URL, if not, then I give them a pre-defined query string for the URL.
I can't get a working jsfiddle, as something weird is going on with the & signs for my query string, sigh.
Basically, I cannot get the URL to change on click.
So here's my code, and the non-working jsfiddle for those interested: http://jsfiddle.net/9uk68m6x/
<form>
<input type="text" class="name">
<input type="text" class="amount">
<script type="text/javascript">
$(function() {
$('.makeUrl').click(function(){
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
if (nameVal != ''){
//if name value isn't blank, then
$("a.makeUrl").prop("href", url+'&name='+nameVal+'&free_amount=1&amount='+amountVal+'00');
}
else (nameVal == ''){
$("a.makeUrl").prop("href", "http://www.website.com&free_amount=1&amount=200");
}
});
});
</script>
Donate
</form>
There is a syntax error in your script: else do not accept any kind of arguments. Use else if instead. However, since your condition is binary (nameVal is either empty or not), then you can actually make do without the second if statement.
Therefore, some changes I have made:
Revise the conditional statement. You simply have to check if nameVal is empty or not using the expresison !nameVal.
Change the href attribute using .attr() instead of .prop().
Use $(this) in the click function since it is cached
Here is the fiddle: http://jsfiddle.net/teddyrised/9uk68m6x/4/
$(function () {
$('.makeUrl').click(function (e) {
// Declare variables
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
// Conditional statement
if (nameVal) {
//if name value isn't blank, then
$(this).attr("href", url + '&name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00');
} else {
$(this).attr("href", "http://www.website.com&free_amount=1&amount=200");
}
// Check updated href
console.log($(this).attr("href"));
});
});
You need to have a ? in there somewhere. A valid parameterized URL would be:
"http://www.website.com/?free_amount=1&amount=200"
Yeah, that is kinda hard to fiddle when they encode those characters for you before it runs.
After a couple changes to your JS, it seems to be working, at least in JSFiddle.
$(function () {
$('.makeUrl').click(function () {
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
if( nameVal !== "" ) {
//if name value isn't blank, then
$("a.makeUrl").prop("href", url + '?name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00');
} else {
$("a.makeUrl").prop("href", "http://www.website.com?free_amount=1&amount=200");
}
});
});
You had a syntax error at the else. Remove the (newVal == '') or use else if
Anyway, here is a working jsfiddle what is show you the URL. (Prevent to activate the link, because of e.preventDefault();
And it's checkin the amountVal also.
<form>
<input type="text" class="name">
<input type="text" class="amount">
<script type="text/javascript">
$(function() {
$('.makeUrl').click(function(e) {
e.preventDefault();
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
var newUrl;
if (nameVal !== '' && amountVal != '') {
//if name value isn't blank, then
newUrl = url + '?name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00';
$("a.makeUrl").prop("href", newUrl);
} else {
newUrl = 'http://www.website.com&free_amount=1&amount=200';
$("a.makeUrl").prop("href", "http://www.website.com?free_amount=1&amount=200");
}
$('#url').html(newUrl);
});
});
</script>
Donate
</form>
<div>URL is: <span id="url"></span></div>
I'm trying to do something similar to this:
$('#dropdown1').change(function() {
window.location = $(this).val();
});
I need to build a page with 2 dropdown lists and a textbox, and I need the values for each one to be stored and then appended to the URL when the form is submitted.
The URL needs to look similar to this when all options have been selected:
http://www.domain.co.uk/search-results/?searchOptions=dropdown1=value1|dropdown2=value2|textarea1=value3
I've figured out how to store the values of the dropdowns but I can't seem to append it to the url.. Here's where I got to:
<script type="text/javascript">
function getValues() {
var priceTo = document.form.priceTo.value;
//alert (priceTo);
}
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo
return false;
});
});
</script>
<body>
<form id="form" name="form">
Price:
<select name="priceTo" id="priceTo" onchange="getValues()">
<option value="5000">Up to £5,000</option>
<option value="10000">Up to £10,000</option>
<option value="20000">Up to £20,000</option>
<option value="40000">Up to £40,000</option>
<option value="80000">Up to £80,000</option>
</select>
<input type="submit" id="submit" value="submit"/>
</form>
</body>
For some reason this goes to:
http://www.domain.co.uk/search-results/?searchOptions=priceto=[object%20HTMLSelectElement]
EDIT:
I finally got it working on most browsers, including IE8 with this code:
<script type="text/javascript">
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.selektvolvocars.co.uk/selekt-search-results/?searchOptions='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value + model.options[model.selectedIndex].value + '%7Czipcode=' +document.getElementById('zip').value + '%7Cproximitydistance=50'
e.preventDefault();
});
});
</script>
For some reason though it doesn't work in IE9... makes no damn sense to me, it just spits out a completely jumbled up URL. Any ideas?
your priceTo is the select list. Use the following to get the selected value:
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value
e.preventDefault();
});
If I've understood correctly:
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location = initialURL + $("#priceTo").val() + "|" + $("#anyOtherSelects").val();
e.preventDefault();
});
You can remove the rest of the Javascript.
You can use a little helper function which gets the id of a <select> or <input> element and returns it with its value. For example:
<script type="text/javascript">
//Helper function to return id and value. The id parameter shouldn't have the # sign at its beginning
function getIdVal( id ) {
return id + "=" + encodeURIComponent( $("#"+id).val() );
}
//run this when the document is loaded and ready
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?'
$('#form').submit(function(e) {
window.location.href = initialURL + getIdVal( "priceFrom" ) + "|" + getIdVal( "priceTo" );
return false;
});
});
</script>
Notes:
You get the value of the current <option> selected in a <select> element using $(...).val().
It is a good programming practice to use encodeURIComponent() for encoding the values just to make sure that no strange character is going to break your convention of using = and | as record and field separator in the search query URL.