I'm using ajax function to send select values to my php script, it is working fine but i have issue when there user add multiple data, i have option to add multiple add child in the form, user can add as many fields.
I need a each loop here. This is my code.
<select class="firstpiller" name="firstpiller">
<option value="0">0</option>
<option value="1">1</option>
</select>
<select class="thirdpiller" name="thirdpiller">
<option value="2">2</option>
<option value="3">3</option>
</select>
if (document.querySelector('[name=firstpiller]') != null){
var firstpiller = document.querySelector('[name=firstpiller]').value;
} else {
var firstpiller = null;
}
if (document.querySelector('[name=thirdpiller]') != null){
var thirdpiller = document.querySelector('[name=thirdpiller]').value;
} else {
var thirdpiller = null;
}
var stepVar = firstpiller + "--" + thirdpiller;
Can anyone help how should i write each loop here?
Thanks in advance.
add a common class to the select say you are given a class .myselect, now you can do something like below
var stepvar = '';
$('.myselect').each(function(value){
stepvar += '--' + value.val();
});
alert(stepvar);
I would like to use jquery to change a particular value in the query string by doing a find and replace of that value based on what is selected from a dropdown option on the page. For example:
Let's say we have the following query string on the current page: ?field1=value1&field2=value2&archived=yes
With the dropdown options being:
Non-Archived
Archived
if someone selects "Non-Archived" the jquery function should do a find and replace on the current query string and set archived=yes to archived=no and then refresh the page.
Here's some code that I have now but it doesn't do a find and replace, it just takes what value I select from the dropdown and then changes the page based on the option value set in the drop down html.
<script type="text/javascript" src="/js/jQuery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery("#dropdown").change(function(e){
window.location.href = jQuery("#dropdown").val();
});});
</script>
<select class="dropdown" id="dropdown">
<option value="#" selected="selected">Choose Type</option>
<option value="(set archived=no)">Non-Archived</option>
<option value="(set archived=yes)">Archived</option>
</select>
Any help would be greatly appreciated!
Try this
jQuery
jQuery(document).ready(function () {
jQuery("#dropdown").change(function (e) {
if (window.location.href.indexOf("archived") > -1) {
window.location.href.replace(/(archived=yes|archived=no)/g, "archived=" + jQuery("#dropdown ").val());
} else {
window.location.href += "archived=" + jQuery("#dropdown ").val();
}
});
});
HTML
<select class="dropdown" id="dropdown">
<option value="#" selected="selected">Choose Type</option>
<option value="no">Non-Archived</option>
<option value="yes">Archived</option>
</select>
This seems to work:
JSFiddle Demo
var href="?field1=value1&field2=value2&archived=yes";
var testUrl = $(location).attr('href');
alert('Current URL = ' + testUrl);
jQuery("#dropdown").change(function(e){
if($("#dropdown").val() == "(set archived=no)") {
href = href.replace("archived=yes", "archived=no");
} else if($("#dropdown").val() == "(set archived=yes)") {
href = href.replace("archived=no", "archived=yes");
}
alert(href);
window.location.href = href;
});
I have a URL that does a filter and spits out some products the structure looks like below:
/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=185,223
Now on this there is a sort function and if I was to use this with out filtering as above the URL would look like the below:
/Products/Catalogue.aspx?orderby=price&desc=1&psize=9
If I currently try and filter and then sort, the sort overwrites myfilter, so the filter becomes null and void.
So what I need it do is be aware that IF i have a filter then append the sorting after 'catfilter=' part in the URL so the URL would then look like
/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=8,188&orderby=man&desc=0&psize=36
The gotcha is that there is not always going to be a filter added in which case the URL would be:
/Products/Catalogue.aspx
<select id="listSort" class="NormalTextBox SortCatalogue" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listLength')[getElementById('listLength').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
<option value="?orderby=name&desc=0&">Sort by</option>
<option value="?orderby=price&desc=0">Lowest price</option>
<option value="?orderby=price&desc=1">Highest price</option>
<option value="?orderby=man&desc=0">Brand A-Z</option>
<option value="?orderby=man&desc=1">Brand Z-A</option>
<option value="?orderby=name&desc=0">Title A-Z</option>
<option value="?orderby=name&desc=1">Title Z-A</option>
<option value="?orderby=ref&desc=0">Code asc</option>
<option value="?orderby=ref&desc=1">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listSort')[getElementById('listSort').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
<option value="?psize=9&foo">Page size</option>
<option value="?psize=6">6 per page</option>
<option value="?psize=9">9 per page</option>
<option value="?psize=18">18 per page</option>
<option value="?psize=36">36 per page</option>
</select>
<script type="text/javascript">
var searchString = window.location.search.substring(1);
var i, val;
var params = searchString.replace('?','&').split('&');
var pgsize,pgorder,pdesc,searchstr;
pgsize = 9;
pgorder = 'name';
pdesc = 0;
searchstr='';
for (i=0;i<params.length;i++) {
val = params[i].split('=');
if(val[0]== "psize")
pgsize=val[1];
else if(val[0]== "orderby")
pgorder=val[1];
else if(val[0]== "desc")
pdesc=val[1];
else if((val[0]).toLowerCase()== "search") {
searchstr=val[1];
}
}
document.getElementById('listLength').value='?psize=' + pgsize;
document.getElementById('listSort').value ='?orderby=' + pgorder + '&desc=' + pdesc;
if(searchstr!='') {
searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
document.getElementById('searchtxthdrright').innerHTML= '"' ;
document.getElementById('searchtxt').innerHTML = searchstr;
}
</script>
Ok lets take a step back from the problem. I think you need to add a bit more structure instead of haphazardly adding and removing bits of url code here and there :)
You have tagged the post as jQuery so i'm going to use that although you haven't actually used it in your posted code.
The whole idea is going to be around creating a JavaScript object and using it as a lightweight dictionary, and the jQuery .param() function which will encode it for us at the end.
Lets change the markup to this:
<select id="listSort" class="NormalTextBox SortCatalogue">
<option value="nameDesc">Sort by</option>
<option value="priceAsc">Lowest price</option>
<option value="priceDesc">Highest price</option>
<option value="manAsc">Brand A-Z</option>
<option value="manDesc">Brand Z-A</option>
<option value="nameAsc">Title A-Z</option>
<option value="nameDesc">Title Z-A</option>
<option value="refAsc">Code asc</option>
<option value="refDesc">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength">
<option value="9">Page size</option>
<option value="6">6 per page</option>
<option value="9">9 per page</option>
<option value="18">18 per page</option>
<option value="36">36 per page</option>
</select>
<input type="text" id="searchstr">
<button id="searchbutton">Search!</button>
As you will see I've also thrown in a textbox and a button as you refer to searchstr in your code.
Instead of encoding and extracting we are just going to store some parseable values in the select options. We're also going to use an unobtrusive javascript technique by using the ID to attach an onchange handler rather than injecting the javascript into the markup (this will be added later on).
Now we need to write some JavaScript code that can build us a querystring. Instead of directly building a querystring though we will be making a javascript object. Then later on that will be used to generate the query string.
I've written a search function that just displays the query string we generated rather than redirect the user.
I've also added in some event handlers so this is triggered as your code was triggering.
function getFiltersAsQueryString() {
var $listSort = $("#listSort"),
$listLength = $("#listLength"),
$searchQuery = $("#searchstr");
queryStringDict = {};
// extract page size
queryStringDict["psize"] = $listLength.find("option:selected").val();
// extract sort order and direction
var selectedItem = $listSort.find("option:selected").val();
queryStringDict["orderby"] = /^[a-z]*/.exec(selectedItem)[0];
queryStringDict["desc"] = /Desc$/.exec(selectedItem) == "Desc" ? 1 : 0;
// extract search
queryStringDict["search"] = $searchQuery.val();
return $.param(queryStringDict);
}
function searchWithFilters() {
// normally you would do a window.location here to redirect
alert(getFiltersAsQueryString());
}
$(document).ready(function () {
// wire up our handlers
$("#listSort").change(searchWithFilters);
$("#listLength").change(searchWithFilters);
$("#searchbutton").click(searchWithFilters);
});
And then at the end of the day when you put all this together you get this:
http://jsfiddle.net/rtpHarry/pdhCF/3/
I don't think this is quite a complete solution yet.
Need to add in the cat filter
Probably want to preselect the controls based on the query string?
I just wanted to post this to see if its going in the right direction.
Hugly helpful thank you, ended up going with this some JS and Jquery in up to come up with the complete solution:
<script type="text/javascript">
var searchString = window.location.search.substring(1);
var i, val;
var params = searchString.replace('?','&').split('&');
var pgsize,pgorder,pdesc,searchstr,catfilter;
pgsize = 9;
pgorder = 'name';
pdesc = 0;
searchstr='';
for (i=0;i<params.length;i++) {
val = params[i].split('=');
if(val[0]== "psize")
pgsize=val[1];
else if(val[0]== "orderby")
pgorder=val[1];
else if(val[0]== "desc")
pdesc=val[1];
else if(val[0]== "catfilter")
catfilter=val[1];
else if((val[0]).toLowerCase()== "search")
{ searchstr=val[1]; }
}
document.getElementById('listLength').value='?psize=' + pgsize;
document.getElementById('listSort').value ='?orderby=' pgorder '&desc=' + pdesc;
if(searchstr!='')
{
searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
document.getElementById('searchtxthdrright').innerHTML= '"' ;
document.getElementById('searchtxt').innerHTML = searchstr;
}
if(catfilter)
{
document.getElementById('searchstrdiv').innerHTML= document.getElementById('searchstrdiv').innerHTML + '&catfilter=' + catfilter ;
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.SortCatalogue').removeAttr('onchange');
$('.SortCatalogue').change(function() {newURL();});
$('.PageLength').removeAttr('onchange');
$('.PageLength').change(function() {newURL();});
function newURL()
{
var newParams = document.getElementById('listSort') [document.getElementById('listSort').selectedIndex].value + '&' + document.getElementById('listLength') [document.getElementById('listLength').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');
var oldPathname = location.pathname;
oldPathname = oldPathname.replace('/desc/','/').replace('/orderby/', '/');
document.location.href = oldPathname + newParams;
}
});
</script>
i have a <select> tag
i want redirect user onchange
i got an code and it works fine
the code is
<select onchange="if (this.value) window.location.href=this.value">
<option value="&s=1">1</option>
<option value="&s=2">2</option>
<option value="&s=3">3</option>
<option value="&s=4">4</option>
</select>
The problem here is :
The current link is: http://anlink.com/page.php?categ=4&subc=2
when i change option
i got redirected to http://anlink.com/&s=1
but i want it redirect to
http://anlink.com/page.php?categ=4&subc=2&s=1
So, i want edit the javascript code to something like this
if (this.value) window.location.href=
http://anlink.com/page.php?categ=4&subc=2 + this.value
i did not try this code but i think it will fail
This should work for you:
<script type="text/javascript">
function changeLocation(field) {
loc = String(window.location);
newLoc = loc.replace(/\&s=\d$/gi, "") + field.value;
window.location = newLoc;
}
</script>
<select onchange="changeLocation(this)">
<option value="&s=1">1</option>
<option value="&s=2">2</option>
<option value="&s=3">3</option>
<option value="&s=4">4</option>
</select>
It replaces any instance of &s= with a digit after it with nothing. Then it adds the new value. The reason for this is in case a &s= doesn't already exist.
If you would like the "s" value to change based on the "s" in the URL (i.e. when you load the page you have &s=3 in the URL, you want the select to be on "3" as well), make the following changes:
add onload="adjustS()" to the body
add an id to the select (I used "s")
add the following function:
function adjustS() {
sLoc = String(String(window.location).match(/\&s=\d$/gi)).replace(/\&s=/gi, "");
document.getElementById("s").selectedIndex = Number(sLoc)-1;
}
Try with:
window.location.href += this.value
Edit:
var href = window.location.href;
var re = /&s\=\d$/;
if (re.test(href)) {
window.location.href = href.replace(re, this.value);
} else {
window.location.href += this.value;
}
I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P