JQuery Multi-Select with multiple values - javascript

I have a form where you select a location, this location has a zip code tied to it and is captured in the data-foo value. What I need is an array built upon multiple locations being selected.
An example would be if both would be selected I'd have 65807 => 71118
Form:
<form enctype='multipart/form-data' role='form' action='' method='post'>
<div class="row">
<div class="col-md-3">
<div class='form-group'>
<label for='select'>Destination(s) </label>
<select name='destination[]' style='height: 200px;' multiple class='form-control' multiple='multiple' id='destination' style='lane'>";
<option value='Springfield' data-foo='65807'>Springfield, MO</option>
<option value='Shreveport' data-foo='71118'>Shreveport, LA</option>
</select>
</div>
</div>
</div>
</form>
What I have so far for JS:
$(function(){
$('#origin').change(function(){
var selected = $(this).find('option:selected');
$('#origin_zip').html(selected.data('foo'));
}).change();
});
$('#destination').change(function() {
$('#destination_zip').text('');
var selected = $('#destination').val();
for (var i = 0; i < selected.data; i++) {
$('#destination_zip').data($('#destination_zip').data('data-foo') + selected[i]);
}
});
EDIT:
This is the code that works on building the array with the text, but not the data-foo that I need.
$('#destination').change(function() {
$('#destination_zip').text('');
var selected = $('#destination').val();
for (var i = 0; i < selected.length; i++) {
$('#destination_zip').text($('#destination_zip').text() + selected[i]);
}
});

The following could be used:
$('#destination').change(function() { // Whenever the select is changed
var arr = []; // Create an array
$('#destination option:selected').each(function(){ // For each selected location
arr.push($(this).data("foo")); // Push its ZIP to the array
});
console.log(arr); // will include the ZIP code(s) of selected location(s).
});
jsFiddle example here

Something like this?
(kind of ugly, I know)
$('#destination').change(function() {
var selected = [];
for(i = 0; i < $('#destination').children().length; i++){
selected[i] = $($('#destination').children()[i]).data('foo');
}
console.log(selected);
});
Edit: nevermind, look at #dsg's answer

Related

Bug??? with loading data from model to js

I made a JS function that creates selector tags for the clients of a hotel room. So if my room capacity equals to 4, it creates dynamicly 4 selectors. In my selector tag there are options containing the clients. The options values are the ID of the client, but when I set my options.text to Client's name for example I get an error:
Uncaught ReferenceError: changeFunc is not defined
at HTMLSelectElement.onchange
Here is my function:
<script type="text/javascript">
function changeFunc() {
var elements = document.getElementsByClassName('selector2');
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
}
var selector = document.getElementById('selector');
var selectedValue = selector.value;
console.log(selectedValue);
#foreach (var item in Model.Rooms)
{
<text>
if (#item.RoomID == selectedValue)
{
var selectedValue2 = #item.Capacity;
}
</text>
}
var inputContainer = document.getElementById('for-input');
for (var i = 0; i < selectedValue2; i++)
{
var selector2 = inputContainer.appendChild(document.createElement("select"));
selector2.className = "selector2";
#foreach (var item in Model.Clients)
{
<text>
var optionz = document.createElement("option");
optionz.value = #item.ID;
optionz.text = #item.Name; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
selector2.appendChild(optionz);
</text>
}
}
}
Here is my div that contains all the selectors:
<div id="for-input"></div>
The strange thing is that if I change item.Name to item.ID or item.phoneNumber, it works. So that means it supports integers only for some reason. Then I tried setting the optionz.text to "Hello world" and it worked too!!! That just blew my mind :X
I tought that I have some problem with the model and tried to load the clients into a different selector:
<select>
#foreach (var item in Model.Clients)
{
<option value="#item.Name">#item.Name</option>
}
</select>
It worked too!!!
Where the problem comes from???
Please don't judge me too much, it's my first code in JS! I'm learning it rn :)
Thanks in advance!
Updated! Here is my onchange handler:
<div class="form-group">
<label asp-for="Reservations2.RoomId" class="control-label"></label>
<select asp-for="Reservations2.RoomId" onchange="changeFunc();" class="form-select" id="selector">
#foreach (var item in Model.Rooms)
{
<option value="#item.RoomID">Room #item.RoomID with capacity of#item.Capacity</option>
}
</select>
<span asp-validation-for="Reservations2.RoomId" class="text-danger"></span>
</div>
The solution was so simple! I just needed to put the value in quotes...

Remove all <select> elements after the one that has been selected

I have a list of dynamically generated <selects>s in a form. I need to make it so that if the user decides go back to an earlier <select>, all <select> that come after it will be removed from the page.
My code below will console.log the correct <select> elements to be removed, but if I start removing them, then it stops working. I'm looping using a non-live list, so I'm confused about why it's not working as expected.
HTML:
<form action="#" method="post">
<label for="select1">square 1:</label>
<select name="1" id="select1"></select>
<label for="select2">square 2:</label>
<select name="2" id="select2"></select>
<label for="select3">square 3:</select>
<select name="3" id="select3"></select>
...
</form>
JS (select is the currently selected <select>):
var form = document.getElementsByTagName('form')[0];
var selects = form.getElementsByTagName('select');
for (var i = 0; i < selects.length; i++) {
if (selects[i].name > select.name) {
var eleToRemove = selectsLive[selects[i].getAttribute('name') - 1];
console.log(eleToRemove);
form.removeChild(eleToRemove.previousSibling); // removes label
form.removeChild(eleToRemove);
}
}
It works when it is written correctly
var sel= 2; // for example
var form = document.getElementsByTagName('form')[0];
var selects = form.getElementsByTagName('select');
for (var i = selects.length-1; i >= 0; i--) {
if (+selects[i].name > sel) {
var eleToRemove = selects[i];
console.log(eleToRemove);
form.removeChild(eleToRemove.previousElementSibling); // removes label
form.removeChild(eleToRemove);
}
}

jquery how to fill select option in my form

enter image description here
The json (data) looks like this
guys! I have a little form. Like this:
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
In this little code i receive a json with data from my database:
var data = JSON.parse(response);
console.log(data);
in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:
var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
help me please, how i can fill select with data from 'data'?
THE SOLUTION BY ADEON IS:
var data = JSON.parse(response);
console.log(data);
var select = document.getElementById('activity_2');
for (var i = 0; i < data.data.length; i++) {
select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
}
You need to do these:
1) Your call getelementById should be changed to getElementById otherwise you would receive error.
2) You need to create options string first and then append that string to DOM rather than touching DOM every time you add options. Touching DOM as less as possible is a good idea from performance point of view.
3) To simplify the syntax you can use string interpolation syntax like below:
var select = document.getElementById('activity_2');
//$(select).html('');
var data = [{id:1, name_rom:'a', name_rus:'abc'},{id:2, name_rom:'x', name_rus:'xyz'}];
var options = "";
for (var i = 0; i < data.length; i++) {
options += `<option value=${data[i].id}>${data[i].name_rus}</option>`;//<--string
//interpolation
}
$(select).append(options);
//OR below, so you don't need to call document.getElementById
//$('#activity_2').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
You can loop your data and append option html to your select.
var select = document.getelementById('activity_2');
$(select).html('');
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
Assuming data is an array, you could iterate over it and apply it to the DOM like so.
var optionString = '';
var data = ['John', 'Josh'];
data.forEach(function(dataItem, index){
optionString += '<option value="' + index + '">' + dataItem + '</option>';
});
$('#activity_2').append(optionString);
Here is a working jsfiddle:
https://jsfiddle.net/9ke5fzqo/
You should use add method which accepts as parameter a new Option.
The constructor of Option looks like this: new Option(text,value).
var array=[{
"text":"text1",
"value":"value1"
},{
"text":"text2",
"value":"value2"
}];
var select = document.getElementById('activity_2');
array.forEach(function(item){
select.add(new Option(item.text,item.value));
});
<select id="activity_2" name="activity_2">
You can use $.append in jquery to add new option into a select input.
Html:
<select id="selinput" name="activity_2"> <option value="">Exmaple</option> </select>
Jquery:
$("#selinput").append('<option value="1">value</option>');
Or you can use jquery.selec2 plugin.

Select list - removing appended elements after using getJSON

In my form I have two items selectors. Selecting the first one should always clear the second list (all elements) and populate it with appended options that I get using getJSON. I have tried at least dozen different ways to do it (e.g. .empty(), .find and .remove) but nothing really works. Thanks in advance!
<form id="devuser" action="#" class="form-horizontal form-seperated" method="post">
<div class="form-body">
<div class="col-md-3"><select id="select1" class="form-control select">
<option value="m">M</option>
<option value="f">F</option>
</select></div>
<div class="col-md-3"><select id="select2" class="form-control select">
</select></div>
</div>
</form>
And here goes js code with .empty() example but I also tried .find('option') and .remove().
$("#select1").change(function() {
var userurl = urldv + $(this).val();
$.getJSON(userurl).done(function(data){
for (var i=0, len=data.length; i < len; i++) {
$("#select2").append('<option id="al'+i+'" value="'+data[i].im+'"</option>');
$("#device"+i).append(data[i].dn;
}
});
$("#select1").change(function() {
$("#select2").empty();
});
});
Using .empty() should work to remove all the option elements.
Issues:
(1) You are missing a closing parenthesis on the following line:
$("#device"+i).append(data[i].dn;
(2) You are registering a second change-event handler inside the first when you should be just executing the code that is in that handler:
$("#select1").change(function() {
var $select1 = $(this),
$select2 = $("#select2"),
userurl = urldv + $select1.val();
$select1.attr('disabled', true);
$select2.empty();
$.getJSON(userurl).done(function(data) {
var optionHtml= '';
for (var i = 0, len = data.length; i < len; i++) {
optionHtml += '<option id="al' + i + '" value="' + data[i].im + '"</option>';
$("#device" + i).append(data[i].dn);
}
$select2.append(optionHtml);
}).always(function() {
$select1.attr('disabled', false);
});
});
Note:
The code above shows how you can prevent overlapping ajax calls by temporarily disabling the first select element.
As others have pointed out, it is more efficient to append all the option elements at once.
You can try this out. The idea is to load the JSON values to a variable then .html it into the selectbox.
$(function(){
var JSONvalue = '';
$.getJSON(userurl).done(function(data){
for (var i=0, len=data.length; i < len; i++) {
var JSONvalue += ('<option id="al'+i+'" value="'+data[i].im+'"</option>');
}
});
$("#select1").change(function() {
$('#select2').html(JSONvalue);
});
});

how to access multiple select array data in javascript

I have a multiple select box and I want to access the selected data in javascript.
Here is the code:
<form onsubmit="return false;" id="multisel">
<select name="a[]" id="a" multiple style="width:350px;" tabindex="4">
<option value="Pedro">1</option>
<option value="Alexis">2</option>
<option value="Messi">3</option>
<option value="Villa">4</option>
<option value="Andres">5</option>
<option value="Sergio">6</option>
<option value="Xavi">7</option>
</select>
<button id="btn1" onclick="ajaxmultiselect()" type="submit" class="btn btn-primary">Save changes</button>
<p id="status"></p>
</form>
Here is the code I have tried so far :
<script>
function ajaxmultiselect(){
var input = [];
input = document.getElementById("a").value;
var status = _("status");
if(input == ""){
status.innerHTML = "Fill out all of the form data";
}else {
status.innerHTML = input;
}
}
</script>
When I run the code it only gives the first value.
I tried to access the values in php and it works fine, it passes the value as an array in php. Why isn't it doing the same with javascript?
I also tried to run a loop for the length of the value but that calculates the length of the first selection only.
I want to display all the values that will be selected.
Any help will be appreciated.
You can do the following:
function getSelectedOptions(element) {
// validate element
if(!element || !element.options)
return []; //or null?
// return HTML5 implementation of selectedOptions instead.
if (element.selectedOptions)
return element.selectedOptions;
// you are here because your browser doesn't have the HTML5 selectedOptions
var opts = element.options;
var selectedOptions = [];
for(var i = 0; i < opts.length; i++) {
if(opts[i].selected) {
selectedOptions.push(opts[i]);
}
}
return selectedOptions;
}
and then change your ajaxmultiselect() so you call it like this:
input = getSelectedOptions(document.getElementById("a"));
You will have to iterate for the values tho.
If you are wanting to get multiple selected items you could try something like the following:
function GetSelectedItems() {
var select = document.forms[0].a;
var selectedList = [];
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
selectedList.push(select.options[i].value);
}
}
alert(Array.join(selectedList, ","));
}
For a given <select> element, all of the selected options are in the selectedOptions property. The selectedIndex property has the index of the first selected option, or -1 if there is no selection. Each of the options are the DOM object for that element, so their value is in the value property. So:
function ajaxmultiselect(){
var input = [];
var select = document.forms[0].a;
var status = _("status");
var options = select.selectedOptions;
if(select.selectedIndex == -1){
// no selection
status.innerHTML = "Fill out all of the form data";
}else {
for (var i = 0; i < options.length)
input.push(options[i].value);
status.innerHTML = input.join(", ");
}
}
From there you should be able to derive whatever you want.
document.getElementById('a').options //All Options
This will give you an array of options that you can iterate through.

Categories