Converting a JavaScript function to jQuery - Select option list - javascript

This is literally the first time I've worked with jQuery and I've read the entire chapter in my textbook but am finding a hard time wrapping my head around it. I'm attempting to convert a JavaScript function (a simple option selection drop-down list) to jQuery. I've attempted a few lines of code that I've gotten from the book or from w3schools and api.query but to no avail. I'll try to make this quick and simple, I just cannot understand jQuery for some reason.
What I've attempted usually doesn't work. Before my option list works fine, then I tried experimenting but I didn't get too far.
I also apolgize for the vagueness of the question, I'd appreciate any help!
Here's something I've tried:
$(document).ready( function () {
var c = ???
if ($(c...
calc.js and index.html below it
function selectedCountry() {
var c = document.getElementById("countryChooser").value;
var message;
if (c == "nothing") { //if they selected the default option, error pops up.
alert("Please select a country.");
} else if (c == "usa") {
message = "United States of America";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else if (c == "canada") {
message = "Canada";
document.getElementById("count").innerHTML = "Your country is: " + message;
} else {
message = "Mexico";
document.getElementById("count").innerHTML = "Your country is: " + message;
}
}
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser" onchange="selectedCountry()">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>

Through jQuery you can do it like below:-
Example:-
$(document).ready(function(){
$('#countryChooser').change(function(){ // on change of select
if($(this).val()!=='nothing'){ // if selected value is some country
$('#count').html("Your country is: "+$("#countryChooser option:selected").text()); // get country name and add it to paragraph
}else{
$('#count').html("");
alert('Please select a country.'); // alert for selecting a country
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>

Get an element by id:
var c = $('#countryChooser');
Get the value of this input/select element
var value = c.val();
Set the html of an element using the element id
$('#count').html('some html');
or set the text (html is not parsed this way)
$('#count').text('some html');
You can also handle the events with jQuery
$(document).ready(function() {
$('#countryChooser').on('change', function(event) {
// this is the DOM element with the id 'countryChooser'
// same as the native: var val = this.value;
var val = $(this).val();
// ...
});
});

I have bind the onchange() event of your select list inside the jQuery(document).ready() method. check this out-
// Updated code--
$(document).ready(function (){
$('#countryChooser').on('change' ,function () {
if(this.selectedIndex){
$('#count').html("Your country is: "+ this.options[this.selectedIndex].text);
}else{
$('#count').html("");
alert("Please select a country.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "calc.js"></script> <!--JavaSript link -->
<select name="countrylist" id="countryChooser">
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>

$('#countryChooser').change(function(){
var selectedCountry = $(this).val();
if(selectedCountry == 'nothing'){
console.log('Select A country');
}
else{
$('#count').html('Your country is '+$('#countryChooser option:selected').text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--JavaSript link -->
<select name="countrylist" id="countryChooser" >
<option value="nothing">Select a country</option>
<option value="usa">United States of America</option>
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
</select>
<p id="count"></p>
Please check the code might help you out
thanks

Related

Event listener inside a function

I have a select on my page:
<select id='cat'>
<option value='a'>A</option>
<option value='b'>B</option>
<option value='all'>all</option>
</select>
With a javascript function that handles which options have to be displayed:
function funcName(aList) {
// populates the options for the select tag
$("#cat").on("change", function(){
// some computation;
});
// uses aList to update some div data
}
What I'm trying to do is if the selected option is all, I have to display everything in aList, otherwise based on the selected option I have to display only the related options. Is my usage of onchange event correct?
Initially I thought of making aList global, but after some reading on globals in JS, I got to know it is not a very good practice.
Thanks in advance!
UPDATE: aList contains some string values.
$(function () {
$("#ddl").change(function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
var assignedRoleId = new Array();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
if(selectedValue== "all")
{
$("#ddl option").each(function()
{
if(this.value=="all")
{
assignedRoleId.push();
}
else
{
assignedRoleId.push(this.value);
assignedRoleId.push(" ");
$("#selected").html(assignedRoleId);
}
});
}
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Select something:
<select id="ddl">
<option value="">select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="all">all</option>
</select>
<div id="selected">
</div>

display data related to a dropdown option

I have a drop down list
<select name="column_select" id="column_select">
<option value="col1">1 column</option>
<option value="col2">2 column</option>
<option value="col3">3 column</option>
</select>
On clicking an option i want to display the details of the particular option in the same page.
How can this be implemented using jquery?
function showval(value)
{
var text = $("#column_select option:selected").text();
var string = "Value is: "+value+" and Text is: "+text;
$("#showvalue").html(string);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showvalue">
</div>
<select name="column_select" id="column_select" onchange="showval(this.value);">
<option value="col1">1 column</option>
<option value="col2">2 column</option>
<option value="col3">3 column</option>
</select>
It should help you.
use this jquery
jquery
$('select.column_select').on('change', function(){
var selectVal = $(this).val();
if(selectVal==col1){
// do something
};
if(selectVal==col2){
// do something
};
if(selectVal==col3){
// do something
};
});
You can subscribe to the change event for the select and perform the details display based on the current value in the select:
$("#column_select").on("change", function () {
var value = $(this).val();
// logic based on selected value
});
try this...
$(document).on('change','#column_select',function() {
// Code to write it anywhere on page.
// If you want it to write on `span#spnDisplay` then use this
var selText = $('#column_select option:selected').text();
$('#spnDisplay').text(selText)
});

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

Dynamically update form action based on selected <option>

So, this is what I am trying to do.. I want a dropdown in HTML with a submit button that changes based on the value of the dropdown.
So, when I have this:
<select name="sizes" id="select13">
<option value="All">All</option>
<option value="20x30">20x30</option>
<option value="30x30">30x30</option>
...
</select>
What I need is a button that checks what the value is. If value = 20x30 then use URL www.example.com/20x30
If value is 30x30 then use URL www.example.com/30x30
I am far from a PHP expert, so anyone that is able to set me off in the right direction would be a life saver :)
some simple Javascript would suffice:
<form id="FORM_ID" action="DEFAULT_ACTION">
<select name="sizes" id="select13">
<option value="All">All</option>
<option value="20x30">20x30</option>
<option value="30x30">30x30</option>
</select>
</form>
<script type="text/javascript">
document.getElementById('select13').onchange = function(){
document.getElementById('FORM_ID').action = '/'+this.value;
}
</script>
You might try this:
Javascript:
function goto() {
window.location = "http://www.example.com/"+document.getElementById('select13').value;
}
HTML:
<select name="sizes" id="select13">
<option value="All">All</option>
<option value="20x30">20x30</option>
<option value="30x30">30x30</option>
</select>
<button onclick='goto()'>Go</button>
When you click on the 'GO' button it redirects to example.com/(the selected value).
Here's a JSFiddle with an exmaple.
EDIT to fit your comment:
function goto() {
var selection = document.getElementById('select13').value;
if (selection != 'All') {
//window.location = "http://www.example.com/"+selection;
alert("http://www.example.com/" + selection);
} else {
alert("Error: You must pick something");
}
}
Also, if you want to submit a form and then do the redirection. The PHP code would be as follows:
<?php
//Process your form without echoing anything before the header function.
if($_REQUEST['sizes'] != 'All'){
header('location:http://example.com/'.$_REQUEST['sizes']);
}
else{
header('location:http://example.com/form.php');
}
You'll need an onchange event for your dropdown:
document.getElementById("select13").onchange = function() {
var currentVal = this.value;
if (currentVal == "20x30") {
//do stuff
}
}

Changing the selected option of an HTML Select element

In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';​​​​​​​​​​
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})

Categories

Resources