Getting value from input box, changing url based on certain conditions - javascript

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>

Related

Allow only number digits in input type regex. issue is i am able to type this(1.) , want to prevent it

MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.

how to compare equals '=' in javascript

I am doing a calculator program in javascript and HTML. I have a button with a value '=' in it. In that one when a user click on "=" button in calculator. it should start evaluate the input he/she had given so far. But when a user click '=' button i tried to compare like this
$(".calcinput").click(function () {
var res = $(this).val();
if (res == '=') {
//code to handle when '=' is pressed;
}
}
but it didn't work please help me.
Your code is good enough to handle the event .. Just add an extra = in comapre
$(".calcinput").click(function () {
var res = $(this).val();
//if (res == '=') {
if (res === '=') {
//code to handle when '=' is pressed;
}
});
Next check where you used div or button or something else element to represent the button =
If it is button then use val() to extract the value
var res = $(this).val();
If the element is div then it could be innerHTML or innerTEXT
var res = $(this).innerHTML;
//Or
var res = $(this).innerText;
You can add an extra line to check whether you getting proper value of element
var res = $(this).val();
alert(res);
You can also use $(this).val() provided you have non empty value attribute in the button
HTML
<button class ="calcinput" type ="button">1</button>
<button class ="calcinput" type ="button">2</button>
<button class ="calcinput" type ="button" value="=">=</button>
JS
$(".calcinput").on('click',function(){
if($(this).val() === "="){
alert("equal");
}
})
WORKING FIDDLE
use
$(this).text()
to retrieve button text instead of
$(this).val()
in your code
= is text of button element and not value. Due to which .val() returns empty string. hence you need to use .text() instead of .val here:
$(".calcinput").click(function () {
var res = $(this).text();
if (res == '=') {
//code to handle when '=' is pressed;
}
});
check out this Demo . I have done a operation for ADD Simillarly you can do it for all operations ..keep it simple
A<input type="text" class="a" /><br/>
B<input type="text" class="b" />
<input type="button" class="calcinput" />
$(".calcinput").click(function () {
var res1 = $(".a").val();
var res2 = $(".b").val();
alert(parseFloat(res1) + parseFloat(res2));
});

JavaScript userinput URL without holding my domain

I'm having a little trouble with JavaScript. My problem is that I have a user input box (where a user would enter a URL) - and a button (when clicked, it will open the URL that the user has typed in the input box).
Here is my code:
<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>
<script>
function myFunction()
{
var x = document.getElementById('userurlbox').value;
if (x == "")
{
alert('Please enter a URL');
}
else
{
window.open(x ,'_blank');
}
</script>
The problem is that the URL opens like this:
http://mywebsite.com/USERURL
I want it to open like this:
http://USERURL
This code only adds the 'http://' if it is not already included:
function myFunction() {
var x = document.getElementById('userurlbox').value;
if (x == "") {
alert('Please enter a URL');
}
else {
if (x.substr(0,4).toLowerCase() === 'http') { // only test first 4 characters as we want to allow both http:// and https://
window.open(x ,'_blank');
}
else {
window.open('http://'+x);
}
}
}
I just tested, you need to include the 'http://' in the window.open
<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>
<script>
function myFunction(){
var x = document.getElementById('userurlbox').value;
x = x.replace('http://'.''); // remove http:// just in-case it is there
if (x == "")
{
alert('Please enter a URL');
}
else
{
window.open('http://' + x ,'_blank');
}
}
</script>
I'm not sure if you can override the relative/absolute url behavior just using the window.open function, so a viable solution would be to check if the url begins with https?:// and prepend '//' if it does not. A url starting with // will always be treated as absolute.

Append multiple dropdown values to URL

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.

Set counter when error message is displayed

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>

Categories