Append multiple dropdown values to URL - javascript

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.

Related

how to add multiple value to datalist

Iam trying to do autocomplete input box. Datalist rows are from JSON. I want that user sees name of the city (data[i].stationName below) while making his choise, but i would like to get that data[i].stationShortCode as a return attribute instead of name when city is selected.
Is that possible to do that way without that user needs to see that shortcode?
I tried to put those in array, but iam not figured out how that would help me or..
My js below:
$(document).ready(function(){
var url="https://rata.digitraffic.fi/api/v1/metadata/stations";
var stations=[];
var elem;
$.getJSON(url,function(data,status){
if(status=="success"){
$.each(data, function(i, item){
if(data[i].passengerTraffic!=false){
elem=$("<option value="+data[i].stationName+ ">");
elem.appendTo('#stations');
//stations[i]={value: data[i].stationName, data:data[i].stationShortCode};
}
else{
}
})
}
else{
console.log("Something went wrong");
}
})
});
And html:
<div class="stationSearch">
<input type="text" list="stations" id="station" placeholder="Valitse Asema"/>
<datalist id="stations"></datalist>
<button class="pick">Paina</button>
The idea of an array is OK, but it better be an object (or Map) so that you have direct access:
var stations = {};
// ...
$("<option>").attr("value", data[i].stationName).appendTo('#stations');
stations[data[i].stationName] = data[i].stationShortCode;
Now when you have the input value in an event handler (e.g. after button click), then get the short code from the input value like this:
var selectedShortCode = stations[$("#station").val()];
Here is working snippet:
var url="https://rata.digitraffic.fi/api/v1/metadata/stations";
var stations = {};
$.getJSON(url, function(data,status) {
if (status=="success"){
$.each(data, function(i, item){
if(item.passengerTraffic){
$("<option>").attr("value", item.stationName).appendTo('#stations');
stations[item.stationName] = item.stationShortCode;
}
});
}
else{
console.log("Something went wrong");
}
});
// ...
$("#station").on("input", function () {
$("#code").text(stations[$(this).val()]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" list="stations" id="station" placeholder="Valitse Asema"/>
<datalist id="stations">
<option value="shortcode">longcode</option>
</datalist>
Code: <span id="code"></span>
Yes, modify your script where you build the <option> elements as such:
if(data[i].passengerTraffic!=false){
elem=$("<option value=" + data[i].stationShortCode + ">" + data[i].stationName + "</option>");
elem.appendTo('#stations');
}
This will generate <option> elements where the "stationShortCode" is the option value and the "stationName" is the displayed value.

Need a way to get an attr from one of many of the same elements

I'm trying to access the id of an element, and slice off the num to piece together a url for an ajax call. I'm mainly using JQuery.
I have experimented with .attr() and .data() and found that they only return the first match, so everytime it would 1, no matter if I clicked on 1, 4, or 54.
.get() only returns the HTML header object, and I haven't yet found a way to access that and possibly pull out an id num.
The code:
$('.display').click(function(event) {
event.preventDefault();
//get category from h4's parent div
let $parent = $('h4').parent();
let $cat = $parent.attr('class');
let cat = String($cat);
//get id to search for...currently only returning id_1, not unique id
let $id = $('h4').get(); //need correct method here
console.log($id);
//slice off num to use in ajax url req
if($id.length == 4) {
id_num = $id.slice(-1) + '/';
} else if ($id.length == 5) {
id_num = $id.slice(-2) + '/';
} else {
id_num = $id.slice(-3) + '/';
}
console.log(id_num);
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/' + $cat + id_num,
success: function(result) {
console.log(result);
}
})
<div class="container">
<h3 id="title">I made the Kessel Run in 12 parsecs.</h3>
<form id ="searchParams" method="POST">
Now, I want to know about the
<input list="cats" name="cats">
<datalist id="cats">
<option id="people" value="people"></option>
<option id="planets" value="planets"></option>
<option id="films" value="films"></option>
<option id="species" value="species"></option>
<option id="vehicles" value="vehicles"></option>
<option id="starships" value="starships"></option>
</datalist>
in Star Wars.
<input id="getInfo" type="submit">
</form>
<div class="display"></div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/twelveparsecs.js"></script>
</body>
</html>
Thank you!
your javascript can't be right to the html snippet, it starts with failures on line 2
let $parent = $('h4').parent();
// never matches on your code, you have no h4 tag
let $cat = $parent.attr('class');
// attr is no function of undefined, null pointer exception
the way to a id can be this this;
<div id="test">
<script>
console.log($('div').attr('id'));
</script>
if a tag is given more than 1 time you will get back a array of JQuery object matching on the nodes with the $('div') selector:
<div id="1">a</div>
<div id="2">b</div>
<script>
let listOfElements = $('div');
for(var i = 0; i < listOfElements.length; i++) {
var singleElementInList = $(listOfElements[i]);
var id = singleElementInList.attr('id');
console.log(id);
}
</script>
the get command is a ajax call to read a response of a url fast

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.

PHP/JavaScript Not affecting selectbox

I created JavaScript bellow the $titleBlock, and when I load the page, it's not affecting the select-box. What should I change?
$titleBlock->addCell(
'<select id="my-select" size="1" class="text" name="user_id">
"'.$option_str.'"
</select>'
);
<script type="text/javascript">
var mySelect = document.getElementById('my-select');;
var setBgColor = function (select) {
select.style.color = select.options[select.selectedIndex].style.color;
};
mySelect.onchange = function () {
setBgColor(this);
document.form_buttons.submit();
};
if(-1 != mySelect.selectedIndex) {
setBgColor(mySelect);
};
</script>
what do you see in log? when
if(-1 != mySelect.selectedIndex) {
console.log(mySelect.selectedIndex);
setBgColor(mySelect);
}
If nothing then that means you are not at all getting handle of select box try to put the script in onload and then try that should work

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

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>

Categories