how to append something to javascript variable - javascript

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;
}

Related

Option selected value onchange

Hello this is my current code:
<select id="link_course">
<option value="">Select Course</option>
<option value="ALL">ALL</option>
<option value="BSIT" selected>BSIT</option>
<option value="BSA">BSA</option>
<option value="BSBA">BSBA</option>
<option value="BSHRTM">BSHRTM</option>
</select>
<script>
$("#link_course").change(function()
{
document.location.href = "home.php?course=" + $(this).val();
});
</script>
If you click any of those options, for example BSBA, it will go to home.php?course=BSBA, and also you can see that the selected attribute is on the option BSIT. What I wanted to do is whenever I click another link, for example BSHRTM, the selected attribute will go to BSHRTM like it would be <option value="BSHRTM" selected>BSHRTM</option>. Any thoughts?
You can do selection via JavaScript :
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
if(getQueryVariable('course') != false) {
$('#link_course option[value="' + getQueryVariable('course') + '"]').prop('selected', true);
}
Reference
After loading the new page, you need to run JavaScript code to set the value on the correct item from the list.
Use window.location.hrefto get current URL. Then check on which page is user currently on and finally select corresponding option.
if(window.location.href.indexOf('home.php?course=BSHRTM)') != -1) {
$('select#link_course option[value=BSHRTM]').attr("selected","selected");
}
To avoid code duplication see Parse query string in JavaScript
You should do it in PHP:
<option value="BSHRTM" <?php if($course == 'BSHRTM') echo 'selected';?>>
Supposing that you previsously set $course = $_GET['course'];

JQuery Find And Replace Query String in URL Based on HTML Dropdown Selection

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;
});

Check if GET variable is already set

I have this code that adds ?prside=5 for example. However, if you change this and the url already is &prside=5, it just appends it again (&prside=5&prside=40).
How do i update it instead of appending it, if it's already present?
<select name="prside" onchange="document.location.href = document.location.href + \'&prside=\' + this.value">
<option>Annoncer pr. side</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="40">40</option>
</select>
EDIT:
There is other GET variables in the real URL too. And the above script does work, it's just not very pretty with multiple &prside
You could check for the existence of prside using the string indexOf method, then you could use a regular expression to replace the value if it exists:
href = document.location.href;
if(!~href.indexOf('prside'))
document.location.href = href + 'prside=' + this.value;
else
document.location.href = href.replace(/(prside=)\d+/, '$1' + this.value)
Here is a one liner if you want to put it straight into the HTML
document.location.href = !~document.location.href.indexOf('prside') ? document.location.href + 'prside=' + this.value : document.location.href.replace(/(prside=)\d+/, '$1' + this.value);

How to HIDE element based on IF statement when onClick is used

I need to be able to hide an image that appears when clicking on an option within a select field ONLY if the value="" (nothing inside quotes). If the value="some_url" inside the option, then I want the image to show.
I have used the following code to SHOW the image when an option is clicked. But when using onClick, it shows the image even if the option value="".
Here is the Javascript I'm using:
function showImage() {
document.getElementById('openimg').style.display = 'block';
Here is the html:
<select name="" >
<option value="url" onclick="showImage();">Some_option_1</option>
<option value="">Some_option_2</option>
<option value="">Some_option_3</option>
</select>
<a href='url_2'><img src='images/some_img.jpg' id='openimg' style='display:none'></a>
I only inserted one onClick command inside one option, just to show that it works. It seems I need an if statement to "show if" or "hide if" along with the onClick command within each option.
this is how I would do it:
<script type="text/javascript">
function showImage()
{
var choice = document.getElementById('myDropDown').value;
if(choice.length > 0)
{
document.getElementById('openimg').style.display = 'block';
}
else
{
document.getElementById('openimg').style.display = 'none';
}
}
</script>
<select id="myDropDown" onchange="showImage()">
<option value="url">Some_option_1</option>
<option value="">Some_option_2</option>
<option value="">Some_option_3</option>
</select>
<a href='url_2'><img src='images/some_img.jpg' id='openimg' style='display:none'></a>
Um, are you asking how to use an if or how to determine what is selected?
First of all, use onchange event in the dropdown.
This is the LONGHAND way of doing it for illustration purposes.
function onChange(){
var mySelect = document.getElementById("my-select");
var selectedValue = "";
for( var i = 0; i < mySelect.length;i++){
if( mySelect[i].selected)
selectedValue = mySelect[i].value;
}
if( selectedValue == "whatever")
{
//do something
}
if( selectedValue == "ugh")
// do something else
}

How do I programmatically set the value of a select box element using JavaScript?

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

Categories

Resources