Call a javascript function from select element in HTML - javascript

function Myfunc(obj1)
{
alert(obj1.prop('outerHTML'));
}
<select id="myselect" onchange="MyFunc(jQuery(this))">
<option value="v1">Value 1</option>
<option value="v2">Value 2</option>
<option value="v3" selected="selected">Value 3</option>
</select>
I have the above two snippets.
When i do alert of the object i get the complete <select&tg; tag along with all it's options.
But, What i want is the object passed should only just be the option which i have selected and not the complete select element block.

Instead of outdated onchange you can use jQuery $('selector').change(function() { });
Fiddle.
Simplified HTML:
<select id="myselect">
<option value="v1">Value 1</option>
<option value="v2">Value 2</option>
<option value="v3" selected="selected">Value 3</option>
</select>
JS:
$(document).ready(function()
{
$('#myselect').change(function()
{
alert($(this).find(':selected').text());
});
});
Update. If you need selected <option> outer HTML, then it can be:
Fiddle.
$(document).ready(function()
{
$('#myselect').change(function()
{
alert($(this).find(':selected')[0].outerHTML);
});
});

Try:
onchange="MyFunc(jQuery(this).find('option:selected'))"

Use as
function MyFunc(obj1)
{
alert($("#myselect option:selected").text());
}
DEMO
OR You can use
function MyFunc(obj1)
{
alert($("#myselect option:selected").html());
}
DEMO

You can pass object or you can fetch selected option in function.
To get selected option html in function use below code -
NOTE - please correct spelling of function either in onchange or function declaration.
function MyFunc(obj1)
{
var value = obj1.value;
var optionHTML = $(obj1).find('option[value="'+value+'"]');
alert($('<div>').append(optionHTML.clone()).html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="myselect" onchange="MyFunc(this)">
<option value="v1">Value 1</option>
<option value="v2">Value 2</option>
<option value="v3" selected="selected">Value 3</option>
</select>
Another way is to bind change event handler using jquery and get the option html
$('#myselect').change(function(){
var value = $(this).val();
var option = $(this).find('option[value="'+value+'"]');
var optionHTML = $('<div>').append(option.clone()).html();
alert(optionHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<select id="myselect">
<option value="v1">Value 1</option>
<option value="v2">Value 2</option>
<option value="v3" selected="selected">Value 3</option>
</select>

You can use :selected selector follows:
$(document).ready(function() {
$('#myselect').on('change', function() {
alert($(this).find('option:selected').eq(0));
});
});

Related

Swap a select text with javascript?

I have a example code here:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
I want to swap se1 and se2 . Here is my code i tried:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
It's work but it require Jquery 1.2.3 but i want to use Jquery 2.1.3. If i change script url to "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" but it isn't work
Thanks for help!
You shouldn't be swapping the values or the text of the two selected items in the lists. You just need to swap which item is selected in each list. Once that is done, that option will have whatever value the list has set up for it.
The version of JQuery you use here doesn't matter since what you are doing requires JQuery operations that have been in JQuery since the beginning.
var sel1 = $("#se1");
var sel2 = $("#se2");
function swap() {
let selection1 = sel1[0].selectedIndex; // Store the first list's selection
sel1[0].selectedIndex = sel2[0].selectedIndex;
sel2[0].selectedIndex = selection1;
// Test
console.log(sel1.val(), sel2.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>

Change value of select list with value of another select list jquery

How can I change the value of a select list with the value of another select list
<select class="main-filter" id="Test1" name="Test1"><option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Need to replace #ReplaceThisText# with value selected from above select box
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Chnage Value</option>
</select>
I have tried code from this link Change the Text of a Option with jQuery
and jquery how to find and replace a selected option that has a certain value
but cannot seem to get it to work
My code is
$('#Test1').change(function () {
sessionStorage.setItem("Test1", $(this).val());
$('.main-filter :selected:contains("#ReplaceThisText#")').val($(this).val());
location.href = $(this).val();
});
:contains will look at the .text() value - but your #ReplaceThisText# is not in the .text() value - so you'll need to use .filter() to find it instead:
Adding some console.logs so you can see what's happening and updated the .val(newval) code to make the replacement.
$('#Test1').change(function() {
var newval = $(this).val();
console.log("before", $(".main-filter :contains('Change Value')").val())
var opt = $('.main-filter option').filter(function() {
return $(this).val().indexOf("#ReplaceThisText#") >= 0;
});
console.log("opt length", opt.length);
opt.each(function() {
$(this).val($(this).val().replace(/#ReplaceThisText#/gi, newval));
});
console.log("after", $(".main-filter :contains('Change Value')").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="main-filter" id="Test1" name="Test1">
<option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Change Value</option>
</select>

Jquery $(document) on change returning null value for deselection

I'm using a Django form, and modifying an option list (in HTML) for one of the fields using $(document) on change for a different field in the form. When I select an option (multiple choice list, can select more than one - not checkboxes),
this.value
returns the correct value. However, when I deselect the option,
this.value
returns null. Why would this be the case? Is a value only returned when something is selected (as opposed to deselected)? If so, how can I get the value of the element that was deselected
Here is my code:
$(document).on("change", "#name2", function () {
var url = #the url I'm using
url += "&field=" + this.value + "&visible=1";
value = this.value
...etc
jQuery val() will return an array of values on a <select multiple> or null (depending on version):
$(document).on('change', '#name2', function() {
var val = $(this).val()
console.log(val ? val : 'None selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select size="20" id="name2" multiple="">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
<option value="6">Item 6</option>
<option value="7">Item 7</option>
<option value="8">Item 8</option>
<option value="9">Item 9</option>
<option value="10">Item 10</option>
</select>
You can iterate .selectedOptions property of <select> element with multiple attribute set to get the .value of each selected <option> element at change event
function getOptionValues(options) {
return Array.from(options, function(el) {
return el.value
})
}
document.querySelector("select")
.onchange = function() {
console.log(getOptionValues(this.selectedOptions))
}
<select multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

JavaScript pass argument this.value to function

Here is my javascript code, i want to pass current selected value of the option to my js function, in this code i used static number 6.
<select name='project_name' class='required input_field' id='project_name' onchange="sendRequest('GET','getClientName.jsp?ProjectId=6')">
<option value=''>-- Select --</option>
<option value="1">Project 1</option>
<option value="2">Project 2</option>
<option value="3">Project 3</option>
</select>
help me to solve this...
Change the string 'getClientName.jsp?ProjectId=6' to
'getClientName.jsp?ProjectId=' + this.options[this.selectedIndex].value)
or
'getClientName.jsp?ProjectId=' + this.value)
but I think the first one is more browser compatible.
var selectBox = document.getElementById('project_name');
selectBox.addEventListener('change', function() {
sendRequest('GET', 'getClientName.jsp?ProjectId=' + this.value);
});
It will help you to get the selected option value . Try this link http://jsfiddle.net/xyaaa/9/.
<html>
<head>
<script>
function getOption(t){
var val;
var options = t.options;
for(var i=0,len=options.length;i<len;i++){
var option = options[i];
if(option.selected){
val = option.value;
}
}
return val;
}
function sendRequest(method , url){
console.log(url);
}
</script>
</head>
<body>
<select onchange="var x=getOption(this);sendRequest('GET','getClientName.jsp?ProjectId='+x)">
<option value="1">Project 1</option>
<option value="2">Project 2</option>
<option value="3">Project 3</option>
</select>
</body>
</html>

javascript onclick alert not working in chrome

<select name="history" id="history" >
<option value="history 1" onClick="alert('h1');">history 1</option>
<option value="history 2" onClick="alert('h2');">history 2</option>
<option value="clearhistory" onClick="this.form.submit();" >Clear History</option>
</select>
could someone help me with this script?
i am expecting that whenever the user clicks history 1 ..it will alert h1
the script works in firefox and IE but not in Chrome :(
If you want to use onClick for option element in Chrome, IE, etc., you must use short fix: set onChange attribute of select element to "this.options[this.selectedIndex].onclick()"
use onchange instead of onclick for select lists.
<select name="history" id="history" onchange="historyChanged(this);">
<option value="history1">history 1</option>
<option value="history2">history 2</option>
<option value="clearhistory">Clear History</option>
</select>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function historyChanged() {
var historySelectList = $('select#history');
var selectedValue = $('option:selected', historySelectList).val();
alert(selectedValue);
if (selectedValue == 'clearHistory') {
historySelectList.form.submit();
}
}
$(function() {
alert('my alert');
$('select#history').change(historyChanged);
});
</script>
Use onChange on the select instead of each option. here is the jsfiddle http://jsfiddle.net/tBjkg/
<select name="history" id="history" onChange="alert(this.value);">
<option value="history1">history 1</option>
<option value="history2">history 2</option>
<option value="clearhistory">Clear History</option>
</select>
The alert(this.value) is referring to the value of the option within the select that is currently selected.
In some browsers,
choosing same option second time,
no onchange-event throws.
This helps:
<select onchange="alert/*orwhateveryoudowith:*/(this.value);/*but set:*/this.selectedIndex=0">
<option disabled selected>Choose your Plan</option>
<option value=1>Plan 1</option>
<option value=2>Plan 2</option>
<option value=3>Plan 3</option>
</select>
Although the selected solution works, but here is a more clearer and easy way to do this:
<select name="history" id="history" >
<option value="history 1">history 1</option>
<option value="history 2">history 2</option>
<option value="clearhistory">Clear History</option>
</select>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#history').on('change', function() {
if ( this.value == 'history 1')
{
alert('h1');
// You can also do anything here
}
if ( this.value == 'history 2')
{
alert('h2');
// You can also do anything here
}
if ( this.value == 'clearhistory')
{
this.form.submit();
// You can also do anything here
}
});
});
</script>

Categories

Resources