I am using the jquery select2 plugin for suggestive form fields. I am trying to access the data stored in my original hidden input fields data attribute. I need the data from these attributes so I can send them to a php script via Ajax. Does anyone have any suggestions on how this would be done? I cannot seem to find a answer on google or the official website.
Thanks
You could also try the following. Suppose you have a select, you can add additional information to the options by using standard data-attribute syntax from jQuery, see jQuery data() API.
<select id="product">
<option value="prod_x" data-additional-info="1234X">Product X</option>
<option value="prod_y" data-additional-info="1234Y">Product Y</option>
</select>
Now in your javascript you can get to the option element itself by using .select2("data"), according to api docs - "Gets or sets the selection. Analogous to val method, but works with objects instead of ids". To get to the option object itself you have to go through the element, an array of all the selected options. In the example below the select is not multi value selectable so I always use the first object from the array, in addition to getting the object I wrap the result from ".element[0]" in $() to make it a jQuery object.
// Get the selected option using select2's api...
var selectedOption = $($("#product").select2("data").element[0]);
Now that we have a jQuery object we can use the jQuery data() API as follows to retrieve the arbitrary data stored on the option element.
var additionalInfo = selectedOption.data("additional-info");
The additional info variable will now contain either "1234X" or "1234Y" depending on which one was selected.
Using this you could eliminate the hidden inputs that holds the additional data and tie it directly to the selected option.
Like in the docs:
//Template:
<select>
<option value="0" data-foo="bar">option one</option>
</select>
//Initiate select2
$("select").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
//access custom data
function format(state) {
var originalOption = state.element;
return $(originalOption).data('foo');
}
We can get data attributes for the selected option
var seledted = $("#selectId").select2().find(":selected");
var s = $(seledted).data("data-field");
I ended up accomplishing this by
$(".suggestive-entry").click(function() {
var val = $(this).siblings('input:hidden').attr('data-field');
alert(val);
});
as you can see i used the siblings attribute to get the hidden input closest to the select2 box that generated the click event.
Related
Is it possible to send as one CSV-string all selected values in HTML select element with multiple="multiple" using jquery-select2 library?
I had a similar requirement and could not find any options to accomplish this directly through the Select2 plugin. However, it was easy enough to create a separate input element and synch it on the select's change event.
var $options = $('select#options'),
$optionscsv = $('input#optionscsv');
$options.select2()
.on('change', function() {
$optionscsv.val($options.val());
});
Here's a live example on codepen: http://codepen.io/anon/pen/gpLbLG
I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});
I'm currently in trouble with a select/select2 and jQuery $.clone issue.
In a html form with html select boxes replaced with select2 but the select2 jQuery plugin is not really relevant for this issue.
I experience problems when I use jQuery $.clone(true, true) to get a copy of a form to work on it.
When I try the following:
window.clone = $('#formSelector').clone(true,true);
The selected values are cloned and get lost. See http://jsfiddle.net/straeger/ct31f34c/9/
Even If I try to remove select2 with the call the cloned select boxes do not hold the selected values.
$('select').select2('destroy');
window.clone = $('#formSelector').clone(true,true);
see: http://jsfiddle.net/straeger/dokenyss/1/
A small hack with a big drawback (if no ID is present) is to copy the selected values to the clone:
$clone.find('select')
.each(function(index, value){
var $el = $(value);
$el.val($element.find('#'+$el.attr('id')).val());
});
see: http://jsfiddle.net/straeger/ct31f34c/10/
My question is what would be the correct way to handle such a problem ?
Does anyone know a way to select the counterpart of the original element from the original jQuery element if I have no ID?
Or a way to persist the currently selected option ? via the attribute e.g.
<option value="c" selected>C Value</selected>
I understand that SELECT multiple will let a viewer select multiple items in a dropdown list and then the form submission passes all the selected items. But how does this work in JavaScript when there is no form submission and you're just watching for a select change:
$('#delete_dropdown').change(function(e){
and then looking at $(e.target).val() for the selected values?
Thanks
You can look at this context inside your handler and val() will return the array of elements, with jquery you can do this:
$('#delete_dropdown').change(function(e){
var selectedArray = $(this).val(); //Array of selected values
});
Fiddle
If you are going with vanilla javascript you will need to loop through the options to check which all are selected and add them to suit yourself.
I'm using Chosen Multiple Select
What I want to do is that if user selects any option I want that value and then I will do some functionality depending on that value.
In chosen without multiple select i can get selected value by using foll. code
$(".selectId").chosen().change(function(){
selectedValue = $(this).find("option:selected").val();
});
But in multiple select I get the first selected value again n again
can anybody help me by finding the current selected value in multiple select element??
The Chosen documentation mentions parameters for getting the most recently changed variables.
Chosen triggers the standard DOM event whenever a selection is made
(it also sends a selected or deselected parameter that tells you
which option was changed).
So, if you just want the most recent option selected or deselected:
$(".selectId").chosen().change(function(e, params){
// params.selected and params.deselected will now contain the values of the
// or deselected elements.
});
Otherwise if you want the whole array to work with you can use:
$(".selectId").chosen().change(function(e, params){
values = $(".selectId").chosen().val();
//values is an array containing all the results.
});
Short answer:
You just do this: var myValues = $('#my-select').chosen().val();
Full example:
If you have a select-multiple like this:
<select id="my-select" class="chzn-select" multiple data-placeholder="Choose one or more values...">
<option value="value1">option1</option>
<option value="value2">option2</option>
<option value="value3">option3</option>
</select>
You can get the selected values in an array to doing the following:
// first initialize the Chosen select
$('#my-select').chosen();
// then, declare how you handle the change event
$('#my-select').chosen().change(function(){
var myValues = $('#my-select').chosen().val();
// then do stuff with the array
...
});
your code is gettin the correct selected value.. but since its multiple you need to use loop..or use map to get the selected value and push it into array..
try this
$(".selectId").chosen().change(function(){
var selectedValue = $.map( $(this).find("option:selected").val(), function(n){
return this.value;
});
console.log(selectedValue ); //this will print array in console.
alert(seletedValue.join(',')); //this will alert all values ,comma seperated
});
updated
if you are getting commaseperated values then use split()
var values= $(".selectId").val();
$.each(values.split(',').function(i,v){
alert(v); //will alert each value
//do your stuff
}
try this
$('.selectId:selected').each(function(i, selected) {
var value = $(selected).val();
var text = $(selected).text();
});
The Chosen documentation mentions parameters for getting the most recently changed variables.
$(".CSS Selector").chosen().change(function(e, parameters) {
// params.selected and params.deselected will now contain the values of the
// or deselected elements.
});
This is how I've got it to work. In my html, I've this
<select data-placeholder="Choose a Country..." class="form-control chosen-select" multiple tabindex="4">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="CHINA">CHINA</option>
</select>
Then javascript
// apply chosen-js to the DOM, and store it in a variable.
var chosen = $(".chosen-select").chosen({
no_results_text: "Oops, nothing found!"
});
// inside the change event, we get the value by calling chosen.val()
chosen.change(function() {
console.log('selected tags are', chosen.val());
});