Alert on change of select option using jQuery in console [duplicate] - html

is there anyway i could trigger a change event on select box on page load and select a particular option.
Also the function executed by adding the trigger after binding the function to the event.
I was trying to output something like this
<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>
$(function(){
$('.check').trigger('change'); //This event will fire the change event.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
});
http://jsfiddle.net/v7QWd/1/

Use val() to change to the value (not the text) and trigger() to manually fire the event.
The change event handler must be declared before the trigger.
Here's a sample
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');

To select an option, use .val('value-of-the-option') on the select element. To trigger the change element, use .change() or .trigger('change').
The problems in your code are the comma instead of the dot in $('.check'),trigger('change'); and the fact that you call it before binding the event handler.

Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :
var sortBySelect = document.querySelector("select.your-class");
sortBySelect.value = "new value";
sortBySelect.dispatchEvent(new Event("change"));

$('#edit_user_details').find('select').trigger('change');
It would change the select html tag drop-down item with id="edit_user_details".

Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>

If you want to do some checks then use this way
<select size="1" name="links" onchange="functionToTriggerClick(this.value)">
<option value="">Select a Search Engine</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
<script>
function functionToTriggerClick(link) {
if(link != ''){
window.location.href=link;
}
}
</script>

Based on Mohamed23gharbi's answer:
function change(selector, value) {
var sortBySelect = document.querySelector(selector);
sortBySelect.value = value;
sortBySelect.dispatchEvent(new Event("change"));
}
function click(selector) {
var sortBySelect = document.querySelector(selector);
sortBySelect.dispatchEvent(new Event("click"));
}
function test() {
change("select#MySelect", 19);
click("button#MyButton");
click("a#MyLink");
}
In my case, where the elements were created by vue, this is the only way that works.

You can try below code to solve your problem.
By default, first option select:
jQuery('.select').find('option')[0].selected=true;

Related

How get html select > option tag custom attribute value using jquery?

I have research that in html you can add a custom attribute by simply adding data-* attribute inside html tag. I populate my select > option tag from my database:
<td>
<select onchange='setattr(this)' id='pitemnamerow"+ cnt +"' class='pitemname select2bs4 tselect'>
<option selected='selected'></option>
</select>
</td>
My Jquery and already set my custom tag
for (i in data.branditms) {
$('#pitemname'+brndid.id).append($('<option>', {
value: data.branditms[i]['item_id'],
text: data.branditms[i]['item_name'],
data-um: data.branditms[i]['um'], //custom-tag
}));
DOM result:
<select onchange="setattr(this)" id="pitemnamerow1" class="select2bs4 pitemname tselect select2-hidden-accessible" data-select2-id="pitemnamerow1" tabindex="-1" aria-hidden="true">
<option selected="selected" data-select2-id="81"></option>
<option value="0-RKM51" data-um="PC/s" data-select2-id="84">0-RING 2"DIAMETER</option>
<option value="UYD983" data-um="M" data-select2-id="84">Parts Wheel</option>
</select>
now when i try to access the custom attribute value it says undefine:
function setattr(brnditem){
var test = $(this).find('.pitemname').data('um');
console.log(test);
}
PS: My table row and select > options are also dynamic.
Any idea?
Try checking this:
var test = $(brnditem).find('option:selected').data('um');
also make sure the function was defined right before calling it on the 'select' tag
You should call data() instead attr(), rewrite you code like this :
function setattr(brnditem)
{
var test = $(brnditem).find("option:selected").data('um');
console.log(test);
}

Changing background colour with drop down menu

I am doing some uni work and I am stuck on this bit of code. I have to change the background colour of the page using a drop down menu.
Drop down menu code
<form>
Background colour:
<select id= background>
<option value="White"> White </option>
<option value="Green" > Green</option>
<option value="Black"> Black </option>
</select>
if statement
<script>
function myFunction() {
var sel1 = document.getElementId('background')
if(sel1 =="Green"){
document.body.style.backgroundColor = Green
}
}
</script>
Also here is the button that runs the function
<button onclick="myFunction()">Change Background</button>
in your javascript code
"getElementId" function is wrong.
Please try below code
function myFunction() {
var sel1 = document.getElementById('background').value;
document.body.style.backgroundColor = sel1;
}
To point out your mistakes:
The id attribute of your <select> is missing quotes.
The getElementId function should be getElementById.
You need a proper JavaScript function to handle the actual change, which can be triggered by either click of a button or by the change event in the dropdown itself. I have written a snippet using the latter method, but you can fetch the selectElem from inside the function using either document.getElementById('background') or the modern document.querySelector('#background') if you are required to use a button.
If you use a valid CSS value for background-color in the value attributes of your <option>s, you can use that value without complex switch or if statements.
The this bit in our function call refers to the calling HTML element.
function updateBackgroundColour(selectElem) {
var i = selectElem.selectedIndex; // Get the selected option's index.
if (i < 0) {
return; // Nothing is selected.
}
// Set the background-color CSS attribute of the <body> element to
// the value attribute of the selected option in our <select> element.
document.body.style.backgroundColor = selectElem.options[i].value;
}
<form>
Background color:
<!-- Note the onchange attribute. "this" refers to the changing element. -->
<select id="background" onchange="updateBackgroundColour(this)">
<option value="red">Red</option>
<option value="MediumSpringGreen">Medium Spring Green</option>
<option value="#34495e">Wet asphalt</option>
</select>
<form>
function myFunction() {
var sel1 = document.getElementId('background').value;
if(sel1 =="Green"){
document.body.style.backgroundColor = "Green" ;
}
}
And this should be your html
<select id="background" onchange="myFunction() ">
Simply edit a jQuery script to display a GIF when you click on the dropdown and change the value of background image.

How to call AngularJS function from select > option

I need to call an AngularJS function from selection:
<select ng-model="selection" >
<option onselect="angular.element(this).scope().functionCall('one')">one</option>
<option onselect="angular.element(this).scope().functionCall('two')">two</option>
<option onselect="angular.element(this).scope().functionCall('three')">three</option>
<option onselect="angular.element(this).scope().functionCall('four')">four</option>
</select>
However, the function never gets called.
In the controller,
$scope.functionCall = function(value){
// do stuff with value
}
How can I call the function.
It's recommended that you use ng-change for that matter, the result may be the same as Cyril's, but the code is more readable and testable, also it is considered a better practice:
Here is a plunker demonstrating it in action:
http://plnkr.co/edit/7GgwN9gr9qPDgAUs7XVx?p=preview
app.controller('MainCtrl', function($scope) {
$scope.listOfOptions = ['One', 'Two', 'Three'];
$scope.selectedItemChanged = function(){
$scope.calculatedValue = 'You selected number ' + $scope.selectedItem;
}
});
And the HTML:
<select ng-options="option for option in listOfOptions"
ng-model="selectedItem"
ng-change="selectedItemChanged()">
</select>
Hope that helps. Thanks.
A Little bit to add on Cyril's and Fedaykin answers:
HTML code
<select ng-options="option for option in listOfOptions"
ng-model="selectedItem"
ng-change="selectedItemChanged()">
Controller Code
app.controller('MainCtrl', function($scope) {
$scope.listOfOptions = ['One', 'Two', 'Three'];
$scope.selectedItemChanged = function(){
console.log($scope.selectedItem);
}
});
You will notice that when the select option is changed, a function gets called which will give the you the value of the current selected value.
Here's what you could do :
HTML
<div ng-controller="YourController">
<select ng-model="selection" ng-options="choice for choice in choices"></select>
</div>
YourController :
$scope.choices = ["first choice", "second choice",...]
$scope.$watch('selection', function(newVal, oldVal){
switch(newVal){
case 'first choice':
[do Some Stuff]
break;
case 'second choice':
[do Some Stuff]
break;
default:
[well, do some stuff]
break;
}
}
BTW: I decided to put the options in the javascript, but what you did also works.
EDIT : ng-change VS $watch, see this question
First, onselect is not a angular keyword, It's a normal javascript keyword
You should use ng-change param in select or use like below..,
In HTML code you have to use like this.,
<select ng-model="selection" >
<option onselect="functionCall('one')">one</option>
<option onselect="functionCall('two')">two</option>
<option onselect="functionCall('three')">three</option>
<option onselect="functionCall('four')">four</option>
</select>
and in the controller
function functionCall(value){
//do stuff with value
}

Html DropDownList not generating events

In my web page I use something like this, but when a option is selected, onchange is not fired. I don't know where I have made a mistake. Actually my requirements is that I need to fetch location details based on the city selected, but it is not working here. Is there any other better way to do so?
#Html.DropDownList("cities", ViewBag.cities as SelectList, new { onselect = "getLoca();"});
<script type="text/javascript">
function getLoca() {
alert("yes");
$.post('#Url.Action("getLocations","Home")', { 'id': $("#cities").val() },
function (data) {
$("#loca").html(data).show();
});
}
</script>
EDIT:
This is the generated HTML code
<select id="cities" name="cities" onselect="getLoca()"><option value="0">--City-- </option>
<option value="1">City1</option>
<option value="2">City2</option>
<option value="3">City3</option>
<option value="4">City4</option>
<option value="5">City5</option>
</select>;
<select id="loca" name="loca" style="width: 170px" ></select>
Use onchange instead of onselect.
jsFiddle Demo
onselect does not do what you expect - it fires when the user selects text (you know, by dragging the mouse or holding shift and using the arrow buttons), so it is not applicable to a select box, which has no selectable text. It works on certain input elements (like text) and textareas, or you can use it on the window.
onchange fires when the value of a form element changes - so this is what you need.
Note: using inline event handlers in your HTML is not a good idea most of the time. If you can, use addEventListener instead.

getting the NAME of a select tag with javascript

I haven't found this question anywhere so I'm posting it here.
I have a bunch of select tags that are partially named using VBScript. I want to be able to get the name of a select tag that was called from the onchange event in javascript.
here is the code.
<select name="optWeeks_<%=intLineCnt%>" id = "name" onchange="changeWeek()">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<SCRIPT LANGUAGE = "JavaScript">
function changeWeek(){
var chosenoption = document.getElementsByTagName("select").name
}
</SCRIPT>
The select name - "optWeeks_<%=intLineCnt%>" is optWeeks prefixed with a number
I would like to know if I can get each name of the select tag that is called? Ex. optWeeks_1, optWeeks_2 etc.
Change the call to:
... onchange="changeWeek(this);">
Then you can simply;
function changeWeek(caller) {
var chosenoption = caller.name;
}
You need to get a reference to the element. this will be one in your event handler function. You can pass it to the function you are calling from there:
onchange="var element = this; changeWeek(element)">
I included the variable assignment above for clarity, you don't need it:
onchange="changeWeek(this)">
You can then get the name from the name property on that object:
function changeWeek(element) {
var name = element.name;
I'd generally recommend binding your event handlers with JS rather than HTML, not using HTML 3.2 though:
<select name="optWeeks_<%=intLineCnt%>" id="name">
<!-- … -->
</select>
<script>
var select = document.getElementById('name');
select.addEventListener('change', changeWeek);
function changeWeek(evt) {
var name = this.name;
}
</script>
Or you can use:
onchange="changeWeek(this.name)"
Or: (keep in mind that the changeWeek function will have to already have been defined)
<script>
var select = document.getElementById('name');
select.onchange = changeWeek;
</script>
addEventListener vs onclick -- for information between adding event listeners and the method I provided above.
An alternative JavaScript way:
var selects = document.getElementsByTagName('select');
for(var i in selects)
{
selects[i].onchange = function changeWeek(e) {console.log(e.target.name);}
}
HTML:
<select name="test">
<option>One</option>
<option>Two</option>
</select>
<select name="test2">
<option>One</option>
<option>Two</option>
</select>
Fiddle:
http://jsfiddle.net/bddwW/