How to pass values without using onChange() in HTML but in JavaScript? - javascript

I know this is a simple question. But I couldn't find a way to overcome this issue. All I want is this. I have a drop-down created using select element & when user selecting a city from that drop-down it should be able to pass that selected value to console ( console.log() ). But I am able to pass very first selected value only. I found a way to pass values to console using onChange() with select element as following code.
HTML
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
JS
function getComboA(selectObject) {
var value = selectObject.value;
console.log(value);
}
But in my case, the whole procedure needs to be code without using onChange() in HTML. Because I have to get user inputs from WordPress form and need to make separate JS file from the form. So, I can't add or change HTML code of the form. My code is below.
HTML code
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
<option value="City 4">City 4</option>
<option value="City 5">City 5</option>
<option value="City 6">City 6</option>
<option value="City 7">City 7</option>
</select>
The JS code I used is below.
JS code
var cityVal = document.getElementById("city-selection");
var cityCon = cityVal.options[cityVal.selectedIndex].text;
console.log(cityCon);
Please help me with this issue.

const selectElement = document.querySelector('#city-selection');
const changeHandler = (ev) => {
console.log('Change!', ev.target.value);
}
selectElement.addEventListener('change', changeHandler);
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
<option value="City 4">City 4</option>
<option value="City 5">City 5</option>
<option value="City 6">City 6</option>
<option value="City 7">City 7</option>
</select>

Please take a look on this fiddle:
Fiddle
const selectCites = document.getElementById("city-selection");
selectCites.addEventListener("change", function(e) {
e.preventDefault();
const { srcElement } = e;
const { selectedOptions } = srcElement;
for (let i = 0; i < selectedOptions.length; i++) {
console.log(selectedOptions[i].value);
console.log(selectedOptions[i].text);
}
})
Basically I added a event listener on the select and wait for any changes and then I loop through the selectedOptions in a case you have more than one.

Just add the EventListener to listen for a change-event:
document.addEventListener("change", function() {
var cityVal = document.getElementById("city-selection");
var cityCon = cityVal.options[cityVal.selectedIndex].text;
console.log(cityCon);
}

You can register an external event listener to respond to the change event like this:
document.querySelector('select[name="city"]').addEventListener('change',function(e){
console.log( 'value: %s - Text: %s',this.value, this.options[ this.options.selectedIndex ].text )
});
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
<option value="City 4">City 4</option>
<option value="City 5">City 5</option>
<option value="City 6">City 6</option>
<option value="City 7">City 7</option>
</select>

you cant use target property. like this :
const myCombo = document.getELementByID("myCombo");
myCombo.addEventListener("change" , (e) => {
console.log(e.target.value)
});

Almost all the best alternatives has been given, you can either use pure javascript or jquery
Say this is your HTML codes for Cities in Tanzania:
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
<option value="dar">Dar es Salaam </option>
<option value="mbeya">Mbeya</option>
<option value="mwanza">Mwanza</option>
<option value="dodoma">Dodoma</option>
<option value="arusha">Arusha</option>
<option value="morogoro">Morogoro</option>
<option value="tanga">Tanga</option>
<option value="zanzibar">Zanzibar City</option>
<option value="kigoma">Kigoma</option>
</select>
So your pure javascript can be:
document.getElementById('city-selection').addEventListener('change', function() {
let selectedCity = this.value;
console.log(selectedCity);
});
Jquery:
$('#city-selection').on('change', function() {
let selectedCity = $(this).val();
//let selectedCity = this.value; this will also do the same
//as the above declaration format
console.log(selectedCity);
});
I hope this can be of help to you

Related

get value from list of select

I have list of selection, and I need value of that option. I have coded as below:
HTML code:
<select class="form-select sectionSelect">
<option value="all_section" data-id="rid0">All Section</option>
<option value="id1" data-id="rid1">Section 1</option>
<option value="id2" data-id="rid2">Section 2</option>
</select>
<select class="form-select sectionSelect">
<option value="all_section" data-id="rid0">All Section</option>
<option value="id3" data-id="rid3">Section 3</option>
<option value="id4" data-id="rid4">Section 4</option>
</select>
<select class="form-select sectionSelect">
<option value="all_section" data-id="rid0">All Section</option>
<option value="id5" data-id="rid5">Section 5</option>
<option value="id6" data-id="rid6">Section 6</option>
</select>
Jquery code :
$(document).on("change",".sectionSelect",()=>{
let section_id = $(this).children(":selected").val();
let room_id = [value of 'data-id' attribute of that option]
console.log(section_id);
console.log(room_id);
})
Here, sectionSelect is common class for them all, I have applied on change event on them to detect change. Problem is that I'm getting this object but not able get value of that option.
And one more problem is I also need data-id attribute value of that option.
please help me
You can do it like this:
$(document).on("change", ".sectionSelect", function() {
var selectedOption = $("option:selected", this);
let section_id = selectedOption.val();
let room_id = selectedOption.attr("data-id");
console.log(section_id);
console.log(room_id);
})
This will give you both the Id and data-id of the selected option.
demo
$(document).on("change", ".sectionSelect", function() {
var selectedOption = $("option:selected", this);
let section_id = selectedOption.val();
let room_id = selectedOption.attr("data-id");
console.log(section_id);
console.log(room_id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-select sectionSelect">
<option value="all_section" data-id="rid0">All Section</option>
<option value="id1" data-id="rid1">Section 1</option>
<option value="id2" data-id="rid2">Section 2</option>
</select>
<select class="form-select sectionSelect">
<option value="all_section" data-id="rid0">All Section</option>
<option value="id3" data-id="rid3">Section 3</option>
<option value="id4" data-id="rid4">Section 4</option>
</select>
<select class="form-select sectionSelect">
<option value="all_section" data-id="rid0">All Section</option>
<option value="id5" data-id="rid5">Section 5</option>
<option value="id6" data-id="rid6">Section 6</option>
</select>

If select option value matches text in separate div, add disabled field

I'm using a select field on my site which reloads the page and then adds this to value to a separate div. I want to be able to disable this option if any of the divs have the same value as the option.
<select id="bayname" name="bayname">
<option value="">--Select Bay--</option>
<option value="1">Bay 1</option>
<option value="2">Bay 2</option>
<option value="3">Bay 3</option>
<option value="4">Bay 4</option>
<option value="5">Bay 5</option>
<option value="6">Bay 6</option>
<option value="7">Bay 7</option>
<option value="8">Bay 8</option>
<option value="9">Bay 9</option>
<option value="10">Bay 10</option>
<option value="11">Bay 11</option>
<option value="12">Bay 12</option>
<option value="13">Bay 13</option>
<option value="14">Bay 14</option>
<option value="15">Bay 15</option>
<option value="16">Bay 16</option>
<option value="17">Bay 17</option>
<option value="18">Bay 18</option>
<option value="19">Bay 19</option>
<option value="20">Bay 20</option>
<option value="21">Bay 21</option>
<option value="22">Bay 22</option>
<option value="23">Bay 23</option>
<option value="24">Bay 24</option>
<option value="25">Bay 25</option>
<option value="26">Bay 26</option>
<option value="27">Bay 27</option>
<option value="28">Bay 28</option>
<option value="29">Bay 29</option>
<option value="30">Bay 30</option>
</select>
For example if a user clicks on 'Bay 1' a div will be created like this:
<li id="1509013949" class="cart-select cart-mode-cart">
1
</li>
And then when the page reloads again, i want to create an if statement so if the value from the select is within one of the divs then it should add it as disabled.
I've had ago at doing this using the code below and i can't get it to print out in the console log.
var baynumberoption = $("#bayname option").val();
var baynumber = $(".cart-select a[href='#select']").text();
if (baynumber.indexOf(baynumberoption) >= 0) {
console.log("match found");
}
$("#bayname option") returns all of the options so I think you really want to use the following. Note if you don't want to rely on the inner text of the link, you can also add data attribute like data-id="1" to store the value which can be used like:
$("#bayname option").each(function() {
var val = $(this).val();
if ( $(".cart-select a[data-id=" + val + "]").length > 0 ) {
$(this).attr("disabled", "disabled");
}
});
Some of the syntax may be off but you get the idea.

Hiding the currently selected option

I am surrently having an issue using JQuery. I have 2 select fields.
<select id="cat" name="cat_id">
<option value="2">Cat 2</option>
<option value="3">Cat 3</option>
<option value="4">Cat 4</option>
</select>
<select id="subcat" name="subcat_id">
<option class="subcats cat_2" value="1">Subcat 1</option>
<option class="subcats cat_2" value="2">Subcat 2</option>
<option class="subcats cat_3" value="3">Subcat 3</option>
<option class="subcats cat_3" value="4">Subcat 4</option>
<option class="subcats cat_3" value="5">Subcat 5</option>
<option class="subcats cat_0" value="0">No subcats for this cat</option>
</select>
And here is my JavaScript code
<script type="text/javascript">
var curval = $("#cat").val();
$(".subcats").hide(0);
$(".cat_"+curval).show(0);
$("#cat").change(function(){
var cat = $(this).val();
$(".subcats").removeAttr("selected").hide(0);
if($(".cat_"+cat).length == 0){$(".cat_0").show(0);}
else{$(".cat_"+cat).show(0);}
});
</script>
Here is the problem. When I change the value of the cats select, the options for the subcats are changed correctly. However, the currently selected field is still showing (Even if it doesn't correspond to the current cat).
Any help would be greatly appreciated.
You should change your code a little bit so on the hange event it can add the selected attribute to the first element in the available options :)
var curval = $("#cat").val();
$(".subcats").hide(0);
$(".cat_" + curval).show(0);
$("#cat").change(function() {
var cat = $(this).val();
$(".subcats").removeAttr("selected").hide(0);
if ($(".cat_" + cat).length == 0) {
$(".cat_0").attr("selected", "selected").show(0);
} else {
$(".cat_" + cat).eq(0).attr("selected", "selected");
$(".cat_" + cat).show(0);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="cat" name="cat_id">
<option value="2">Cat 2</option>
<option value="3">Cat 3</option>
<option value="4">Cat 4</option>
</select>
<select id="subcat" name="subcat_id">
<option class="subcats cat_2" value="1">Subcat 1</option>
<option class="subcats cat_2" value="2">Subcat 2</option>
<option class="subcats cat_3" value="3">Subcat 3</option>
<option class="subcats cat_3" value="4">Subcat 4</option>
<option class="subcats cat_3" value="5">Subcat 5</option>
<option class="subcats cat_0" value="0">No subcats for this cat</option>
</select>

javascript function to remove null value

am trying to remove null value in listbox so first i tried with loop and then one guy helped to do this way but its not removing a null value and empty space...can some body
help out this problem by javascript..
<script type="text/javascript">
function change()
{
//document.getElementById("Geography").options[7]=new Option("", "newval", true, false);
var optionsArr = [];
optionsArr.push(document.getElementById("Geography").options);
optionsArr.push(document.getElementById("zone").options);
optionsArr.push(document.getElementById("country").options);
var optArrlenght = optionsArr.length;
for ( var j = 0; j < optArrlenght; j++){
var options = optionsArr[j];
var optionslength = options.length
for (var i = 0; i < optionslength; i++)
{
if (options[i].innerHTML == "Null Value" || options[i].innerHTML == "")
{
options.removeChild(options[i]);
// OR
// options.options[i] = null;
}
}
}
}
</script>
</head>
<body onload="change()">
Geography:<select id="Geography">
<option value="0"></option>
<option value="1">Null Value</option>
<option value="2">item 2</option>
<option value="3">item 3</option>
<option value="4">item 4</option>
<option value="0">All</option>
</select>
zone: <select id="zone" >
<option value="0"></option>
<option value="1">Null Value</option>
<option value="2">item 2</option>
<option value="3">item 3</option>
<option value="4">item 4</option>
<option value="0">All</option>
</select>
country:<select id="country" >
<option value="0"></option>
<option value="1">Null Value</option>
<option value="2">item 2</option>
<option value="3">item 3</option>
<option value="4">item 4</option>
<option value="0">All</option>
</select>
</body>
Hi whether u have found out solution or not still i put my answer here..
http://jsbin.com/awUWAMeN/2/edit
function change()
{
$('select').each(function() {
$(this).find('option:contains("Null Value")').remove();
});
}
This is not the proper way to remove a dom element: .removeChild() should be called on the elements parent. Instead of options.removeChild(options[i]);, try:
options[i].parentElement.removeChild(options[i]);
Also, if you want to remove the element from the array options call the following:
options.splice(i, 1);
You just need to make the following changes:
1.
<option value="0"></option>
<option value="Null Value">Null Value</option>
<option value="item 2">item 2</option>
<option value="item 3">item 3</option>
<option value="item 4">item 4</option>
<option value="All">All</option>
2.Inside Loop in function change you need to do following
if (options[i].value == "Null Value" )
{ options.removeChild(options[i]);}
if(options[i].innerHTML == "")
{ options.removeChild(options[i])}

How to redirect user when clicking an option in a select list?

I'm kicking my self for not being able to do this. But I've tried almost everything. I simply want to redirect a user to a specific page when they click an option in my option value list. Here's my current code (which should explain my question better):
<select name="test_redirect">
<option value="1" onclick="document.location = 'http://localhost/shop?item=1';">Item 1</option>
<option value="2" onclick="document.location = 'http://localhost/shop?item=2';">Item 2</option>
<option value="3" onclick="document.location = 'http://localhost/shop?item=3';">Item 3</option>
</select>
I've also tried onChange as well. Same result. Can some one please help me with this? Thank you guys.
document.querySelectorAll("[name=test_redirect]")[0].addEventListener('change',
function () {
window.location = "http://localhost/shop?item=" + this.value;
});
This depends on a relatively new browser (with querySelectorAll and addEventListener), but the principle's the same. click doesn't get triggered on options, so you have to go with change on the <select>. Might as well consolidate the code a bit too.
http://jsfiddle.net/5n5ZE/
<select id="test_redirect">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
javascript
var val = document.getElementById("test_redirect").value;
window.location.href = "http://localhost/shop?item=" + val;
jquery
$("#test_redirect").change(function(){
var val = $(this).val();
window.location.href = "http://localhost/shop?item=" + val;
});
try this (give the link of the page in value of each option)
<select name="test_redirect" onchange="window.location.href=this.form.test_redirect.options[this.form.test_redirect.selectedIndex].value">
You need to bind the event handler to the <select> and not the individual options:
<select name="test_redirect" onchange="location.assign('http://localhost/shop?item=' + this.options[this.selectedIndex].value)">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
This will save you lines :
<select onchange="location = this.options[this.selectedIndex].value;">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
try this
<select name="test_redirect" onchange="location.href='http://localhost/shop?item='+this.value">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>

Categories

Resources