Trying to assign ticks to a checkbox and have options selected if the value matches the values in the textbox. This a multi-select parameter.
E.g. if the textbox contains 1,2 when the page refreshes I want to ensure Cheese and Tomatoes is selected. If the textbox contains 1,5,6 then I want to ensure Cheese, Pepperoni and Onions are selected. If the textbox contains 1,2,3,4,5,6 then I want to ensure all checkboxes are selected.
Trying to write some javascript to do this. I tried to use local storage but can't get it working. See code example: https://www.codeply.com/go/rupzwTzBMY
ASPX:
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
Currently when the page refreshes, even if the textbox has values assigned - the checkboxes clear and nothing is selected.
I am trying to ensure when users select items from the multi-parameter when the page refreshes those values are not gone and still remain on the page.
Javascript functionality that works so far. This puts values in a textbox when you select items from the drop-down. However, when the page refreshes the text box keeps these selected values but the multi-select parameter doesn't:
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
document.getElementById("txt1").value = selectedOptions;
},
});
Firstly, you must reload the select once after populating default values as below
$('#basic').multiselect('refresh')
Secondly, try to use onInitialized method as described here
Finally, You're trying to assign back values from TextBox to Dropdown as below, where you're trying to assign the value as such with a comma 1,2 which actually doesn't exist as a value in dropdown.
External Fiddle
$('#basic').children("option[value=" +
document.getElementById("txt1").value + "]").prop("selected", true);
Split the values as 1 and 2 and then assign and it works.
$(document).ready(function () {
document.getElementById("txt1").value = "1,2,3"
$('#basic').multiselect({
includeSelectAllOption: true,
numberDisplayed: 5,
onInitialized: function(select, container) {
console.log("Init");
selectListValues();
}
});
$("#basic").multiselect('refresh');
});
function selectListValues()
{
var txtValue = document.getElementById("txt1").value;
var selectedValues = txtValue.split(",");
for(var i = 0; i < selectedValues.length; i++)
{
var val = selectedValues[i];
if (val == null || val == "") continue;
$('#basic').children("option[value=" + val + "]").prop("selected", "selected");
}
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
</head>
<body>
<input type="text" runat="server" id="txt1" visible="true" value="" onchange="selectListValues()" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
</body>
</html>
You can get and populate the value using local storage and split the item.
Note
I had to comment out the local storage so the demo code will work as local storage won't work cross domain. You will need to test this locally.
$(function() {
//$("#txt1").val(localStorage.getItem('topping'));
var str = $("#txt1").val().split(",");
$('#basic').val(str);
$('#basic').on('change', function(){
var list = $("#txt1").val($(this).val());
//localStorage.setItem('topping', list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="1,2,4" />
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
you can store input value in local storage, then get inputvalue from local storage then iterate on option set and set selected attribute to true of option if value is present in localstorage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple>
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
<script>
$(document).ready(function () {
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
console.log(selectedOptions);
setInputAndLocatStorage();
}
});
function onLoad() {
if(!localStorage.getItem('selectedItems')) return false;
var selItems = localStorage.getItem('selectedItems').split(',');
document.getElementById('txt1').value = selItems.join(',');
$('#basic').multiselect('select',selItems);
}
function setInputAndLocatStorage() {
var selItems = $('#basic').val();
var val = selItems == null ? '': selItems.join(',');
document.getElementById('txt1').value = val;
localStorage.setItem('selectedItems', val);
}
onLoad();
});
</script>
Related
when i click button clone is worked but it is showing value only one dropdown list
i want to get value clone multiple dropdown list and show the alertbox
there is my code
$(document).ready(function() {
$('#btnid').click(function() {
$('#idcuntry').clone().attr('id', 'id_' + $(this).index()).insertAfter('#idcuntry');
var a = $('#idcuntry').val();
alert(a);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="idcuntry">
<option value="10">Selection </option>
<option value="20">Pa </option>
<option value="30">India </option>
</select><br/>
<input type="button" value="clone" id="btnid">
The first problem is that you are getting the value of #idcuntry, and there's only one with this ID (which is good, IDs should be unique, so you made the right choice of changing the ID of your clones).
To target multiple elements, you can add a class to them, for example class="countryselect".
Then, .val() will only return the value of the first element. But you can use .map() to get them all in an Array:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btnid').click(function() {
$('#idcuntry').clone().attr('id', 'id_' + $(this).index()).insertAfter('#idcuntry');
var a = $('.countryselect').map(function() {
return $(this).val();
}).get();
alert(a);
});
});
</script>
<select id="idcuntry" class="countryselect">
<option value="10">Selection </option>
<option value="20">Pa </option>
<option value="30">India </option>
</select><br/>
<input type="button" value="clone" id="btnid">
Im trying to loop through multiple text and select boxes in a form and validate they have been answered.
I have used the following code to loop through the text boxes but can work out how to do something similar on the select boxes.
<form name="Form1"></form>
<label>Question 1</lable>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>';
</form>
<script>
(function (){
$('#Go').on('click', function(e){
e.preventDefault();
genericValidationText('form[name="Form1"]');
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationText (formName) {
document.forms.noValidate = true;
var notValid;
// PERFORM GENERIC CHECKS
// INPUT form fields
$(formName + ' *').filter(':input').each(function(){
var formElement = formName + ' input[name="'+ (this.name) + '"]' ;
performValidation(formElement);
});
function performValidation(formElement){
if ($(formElement).hasClass('required')) {
notValid = false;
if (!($.trim($(formElement).val()))){
notValid = true;
};
if (notValid === true) {
showErrorMessage(formElement);
};
};
}
}
function genericValidationSelect (formName) {
?????
}
</script>
You can validate <select> elements in much that same way as <input /> elements, by examining the result of the select element's .val().
Something to keep in mind is that the <select> will have a value by default (that corresponds to the <option> that is initially visible to the user in the browser). This will in effect cause validation on the <select> to pass (even when a selection option hasn't been explicitly picked by the user).
To address this, consider adding a default <option> to the <select> like this:
<option selected disabled>Please select something</option>
Adding this option means that validation on the <select> will fail until the user has actually engaged with the <select> by picking a valid option (after which, validation on the select will pass):
(function() {
/* Consider using submit on form, rather than a click event
listener on the Go button */
$('form[name="Form1"]').submit(function(e) {
e.preventDefault();
/* Exclude call to genericValidationText() for
this snippet to simplify it
genericValidationText('form[name="Form1"]');
*/
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationSelect(formName) {
let notValid = false;
/* Iterate each select in the form */
$('select', formName).each(function() {
/* Check value in similar way. If null value,
then consider the select invalid */
var selectedOption = $(this).val();
if (selectedOption === null) {
notValid = true;
}
});
if(notValid) {
alert('Please select an option');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Fixed : remove closing form tag -->
<form name="Form1">
<!-- Fixed : typo -->
<label>Question 1</label>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<!-- Added default "no value option" to demonstrate validation -->
<option selected disabled>Please select something</option>
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>
</form>
Hope this helps!
The following should work:
const changeEventHandler = e => {
const value = e.target.options[e.target.selectedIndex].value;
console.log(value); //Validate value...
}
const select = document.querySelector('select[name=question3]').onchange = changeEventHandler;
I am using Bootstrap Multiselect plugin for developing a drop-down which includes check boxes.
The values gets sent properly into my DB while submitting. But, while retrieving the same selected data, I can't seem to display multiple values.
When there is just one selected values, it gets displayed perfectly using .val() but when multiple values are present the .val() fails to display anything.
So, I tried searching the Bootstrap Multiselect site and found .multiselect('select',values) method.
Now, the multiple values are getting displayed but there are two dropdowns now.
Maybe because I am calling .multiselect twice. Please help me in displaying multiple values and a single dropdown. Here's my code:
<select id="Damage_#item.Id" name="Damage_#item.Id" class="form-control multiselect" style="margin-bottom: 10px;" multiple="multiple">
<option value="0" selected>Pick One</option>
<input type="hidden" id="Hidden_Damage_#item.Id" name="Hidden_Damage_#item.Id" value="#item.Damage" />
</select>
<script type="text/javascript">
$(document).ready(function () {
//$(function () {
$('.multiselect').multiselect({
onInitialized: function (select, container) {
var selectedDamageValues = $('#Hidden_' + select[0].id).val();
console.log(selectedDamageValues);
var array = selectedDamageValues.split(",");
},
numberDisplayed: 1,
buttonWidth: '100%'
});
//});
});
</script>
You have to use the $(selector).multiselect('select', [array of values]); to assign select item programticly
see below snippet :
$(document).ready(function() {
$('#example-getting-started').multiselect({
enableFiltering: true,
buttonText: function(options, select) {
if (options.length == 0) {
return 'Select Groups';
}
else {
var selected = '';
options.each(function() {
selected += $(this).text() + ', ';
});
return selected.substr(0, selected.length -2);
}
}
});
$('#example-getting-started').multiselect('select', ['one', 'four']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.min.js"></script>
<!-- Build your select: -->
<select id="example-getting-started" multiple="multiple">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
I want to do JavaScript validation for listbox
If Value from Lisbox is not selected, it should get alert "Please Select Your Skill"
But if user select 3 Skill from 6 Skill. I need that 3 skiils should get alert using JavaScript.
Here is my Code...
call script on submit button..
<html>
<head>
<script></script>
</head>
<body>
<form name="registration" id="registration_form_id" action="" method="post">
<select id="skillid1" name="skill[]" multiple="multiple" size="3" >
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit" onClick="myFunction()">Submit</button>
</form>
</body>
</html>
Thank you
Rahul
First of all use onsubmit form event instead of button click. In this case you return false when the form should not be submitted. Here is an example:
function myFunction(form) {
var select = form['skill[]'];
// Check if skill is selected
if (select.selectedIndex === -1) {
alert("Please Select Your Skill");
return false;
}
// Check if selected 3 skills out of 6
if (select.selectedOptions.length) {
var options = [].map.call(select.selectedOptions, function(option) {
return option.text;
}).join('\n');
alert("You selected: \n" + options);
return true;
}
return false;
}
<form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
<select id="skillid1" name="skill[]" multiple="multiple" size="3">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit">Submit</button>
</form>
Note that returning true from event handler will submit the form (in above demo submission is suppressed).
Here is JSFiddle demo.
To get the selected options from a multiple select, you should iterate over the options collection and collect the ones that are selected.
There is also the selectedOptions collection (per dfsq's answer), but support is patchy across browsers.
The looping method is made easier with a simple toArray function:
// Return an array of list members in numeric index order
// Respect sparse lists.
function toArray(list) {
var array = [];
// Use for loop for maximum compatibility
for (var i=0, iLen=list.length; i<iLen; i++) {
// Respect sparse lists
if (list.hasOwnProperty(i)) {
array[i] = list[i];
}
}
return array;
}
So if you have a reference to the select element, you can get the selected options using:
var selectedOptions = toArray(select.options).filter(function(option) {
return option.selected;
});
Now you can show the displayed text of each option in an alert using:
alert(selectedOptions.map(function(option){return option.text}).join('\n'));
I know this is simple, and I need to search in Google. I tried my best and I could not find a better solution. I have a form field, which takes some input and a select field, which has some values. It also has "Other" value.
What I want is:
If the user selects the 'Other' option, a text field to specify that 'Other' should be displayed. When a user selects another option (than 'Other') I want to hide it again. How can I perform that using JQuery?
This is my JSP code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="otherType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
Now I want to show the DIV tag**(id="otherType")** only when the user selects Other.
I want to try JQuery. This is the code I tried
<script type="text/javascript"
src="jquery-ui-1.10.0/tests/jquery-1.9.0.js"></script>
<script src="jquery-ui-1.10.0/ui/jquery-ui.js"></script>
<script>
$('#dbType').change(function(){
selection = $('this').value();
switch(selection)
{
case 'other':
$('#otherType').show();
break;
case 'default':
$('#otherType').hide();
break;
}
});
</script>
But I am not able to get this. What should I do? Thanks
You have a few issues with your code:
you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">
should be <select name="dbType" id="dbType">
$('this') should be $(this): there is no need for the quotes inside the paranthesis.
use .val() instead of .value() when you want to retrieve the value of an option
when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function
try this:
$('#dbType').on('change',function(){
if( $(this).val()==="other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});
http://jsfiddle.net/ks6cv/
UPDATE for use with switch:
$('#dbType').on('change',function(){
var selection = $(this).val();
switch(selection){
case "other":
$("#otherType").show()
break;
default:
$("#otherType").hide()
}
});
UPDATE with links for jQuery and jQuery-UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
Demo on JSFiddle
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
You have to use val() instead of value() and you have missed starting quote id=dbType" should be id="dbType"
Live Demo
Change
selection = $('this').value();
To
selection = $(this).val();
or
selection = this.value;
I got its answer. Here is my code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
And my script is
$(function() {
$('#dbType').change(function() {
$('.selectDBType').slideUp("slow");
$('#' + $(this).val()).slideDown("slow");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>
</body>
</html>
$('#dbType').change(function(){
var selection = $(this).val();
if(selection == 'other')
{
$('#otherType').show();
}
else
{
$('#otherType').hide();
}
});