jQuery Select list, selected text value rather than the value - javascript

building on my last question jQuery getting values from multiple selects together
I have the select list like:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192">Off</option>
<option value="8192">On</option>
</select>
And I basically want to add or subtract the value of the options if it's off, subtract if it's on add it. It's going to be stored in a cookie (it uses bitwise)
The jquery I have is:
<script>
$(document).ready(function(){
var currentAccess = $.cookie("access");
})
$("select").change(function () {
var currentText = $(this).text()
var value = $(this).val()
$.cookie("access", value, { expires: 24 });
alert(currentText);
alert( $.cookie("access") );
})
</script>
I'll do the addition in the change function. The thing I can't work out is how to get the text of the select to do an if statement (so if it's yes, add the value, if it's no, subtract the value)
Tom

If you're looking for the inner text of the selected <option> element, you can use the :selected selector to match it, then call the text() method:
var currentText = $(this).find(":selected").text();
Or, alternatively:
var currentText = $(":selected", this).text();

To get the text of the selected item:
var value = $("#staff_off :selected").text();
I'd also suggest (if you're using HTML5) that using the data-x attribute to store the flag whether to add or subtract the value would be more semantic. Like this:
<select name="access" class="change" id="staff_off" runat="server">
<option value="8192" data-factor="-1">Off</option>
<option value="8192" data-factor="1">On</option>
</select>
Then to get your final value to apply to the total you simply multiply the value by the data-factor attribute.

You can use this $("#staff_off").find("option:selected").html();

Related

How do I get an form selected value jQuery

How should I get an form input selected value using jQuery
<form:select path="amtAppMonitResltVO.monitStat" id="amtAppMonitResltVO.monitStat" cssClass="state">
<option value="">선택</option>
<form:options name="monit" items="${apps}" itemValue="subCd" itemLabel="subCdNm" />
</form:select>
<img src="<c:url value='/resources/img/read.png'/>" class="read" id="appStatSearch"></td>
You just need get the .val() of the amtAppCollInfoVO_mkType select input:
var some_var = $('#amtAppCollInfoVO_mkType').val();
For pure Javascript just switch .val() to .value
Note that your current option does not have a value.
Note that since you have the . in your id you have to add double \ to your Javascript code:
<script>
$(function() {
$('#amtAppMonitResltVO\\.monitStat').on('click', function() {
var moniStat = $('#amtAppMonitResltVO\\.monitStat').val();
console.log(moniStat);
})
})
</script>
Credit goes here for this answer.
The one option you have has no value, but if you set a value for it, you could use a selector like the following to get the value of the first selected option.
$("#amtAppCollInfoVO_mkType option:selected").val()
If you wanted all the option values in an array you could use the map method.
var arr = $("#amtAppCollInfoVO_mkType option").map(function(){return $(this).val();}).get();

jQuery SELECT with Textarea

Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2
You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo
To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.
By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:
Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/

How can I put selected value of jquery multiselect dropdown into a hidden element's id

How can I put selected value of jquery multiselect dropdown into a hidden element's id? I need that id be an array so I can get the selected values of the multiselect into that.
What I tried is:
$( "#Myselect" ).change(function(){
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).val() + " ";
});
document.getElementById("objecttype").value = str;
}).trigger( "change" );
<html:hidden styleId="objecttype" property="objecttype" name="Myobjecttype"/>
but objecttype is just an id and isn't an array!
I assume you want this hidden field to be posted somewhere and used later on (server-side or whatever). Take a look at this Fiddle: http://jsfiddle.net/hm71689h/ it is roughly what you wanted.
Take into account what Haxxxton just said: you're joining the values using a delimiter (in this example a comma by default). You need to split that value into a new array later on.
Also, in your code-sample, you're referring to the hidden field using: document.getElementById("objecttype")
But you did not use an identifier, you used a name. Although you might think it should be the same, an ID is not the same as the name of an element.
I think you need smth like this:
HTML:
<select name="choice" multiple id="mySelect">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="hidden" name="myObjecttype" />
JS:
$('#mySelect').change(function(){
//brand new array each time
var foo = [];
//fills the array
foo = $("option:selected", this).map(function(){ return $(this).val() }).get();
//fills input with vals, as strings of course
$("input[name='myObjecttype']").val(foo);
//logs an array, if needed
console.log($("input[name='myObjecttype']").val().split(','));
});
Don't forget hidden input can't store array-/object- data, only strings. But you can easily make array.
See working jsfiddle: http://jsfiddle.net/sfvx5Loj/1/

jquery, get value of different select list

I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle

How to get the selected option in an html using jquery

I want to retrieve the id of my option that I selected. Over here you can see my HTML.
<select name="zaal" id="zaal">
<DIV CONTENTEDITABLE="FALSE" ID="MACONTAINER" MACONSTRAINT="" MAPARAMETER="ZALEN">
<DIV CONTENTEDITABLE="TRUE" ID="MAITEM">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</DIV>
</DIV>
</select>
I am doing it like this.
var selectVal = $("#zaal :selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
But for some reason it won't work.
Can anybody help?
EDIT
Ok the divs are the problem. But I need those to get my values from my database.So I think I need to find another solution than a select.
$("#zaal option:selected").attr('value'); // will return you ~#ITEM.ID~
To get the id
$("#zaal option:selected").attr('id'); // will return you ZAALNAME
To get id on selection change try this:
$('#zaal').on('change', function() {
// To get id
$('option:selected', this).attr('id');
$('option:selected', this).attr('value'); // return the value of selected option
// To get the select box value
var value = this.value;
});
Maybe try:
$("#zaal option:selected").val();
Also, try moving the divs outside of the select element.
Look at this question:
<div> and <select> tags
You can only put <option> or <optgroup> inside a <select>. If you want to put anything else in there you have to make some kind of list yourself.
Why would you like to put any div inside a select anyway?
If I put the HTML you gave me (with edited strings) inside Google Chome, this is what is made of your code:
<select name="zaal" id="zaal">
<option value="x" id="ZAALNAME">X, Y</option>
</select>
$("#zaal option[value='0']").text()
Try this:
var selectVal = $("#zaal option:selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
The html should be
<select name="zaal" id="zaal">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</select>
$('#zaal').change(function(){
alert($($(this)+':selected').attr('id'));
});
Fiddle http://jsfiddle.net/cBaZ7/1/
val() will retrieve the value of the selected option. It is not the id
So try this:
$("#zaal option:selected").attr("id")

Categories

Resources