Adding multiple select options with jquery - javascript

I've created functionality to move items from the left -> right, and vice versa. On top of that, I am added the option values of each item into a hidden input box, so I can later submit it to the server for processing. It seems that when I try to add more than one item at a time, only the first one is being added to the hidden input box though.
In the end, my hidden input field should look like: 3233,2332,3234,1212,112
Since I'll accept the parameters in the Ruby on Rails server side to parse and do whatever to (unless there's a better option).
Here's my current code:
$("#btnLeft").click(function(){
var selectedItem = $("#hosts_assigned option:selected");
$("#hosts_available").append(selectedItem);
$("#hosts").remove(selectedItem.val());
});
$("#btnRight").click(function(){
var selectedItem = $("#hosts_available option:selected");
$("#hosts_assigned").append(selectedItem);
var current_hosts = $("#hosts").val();
$("#hosts").val(current_hosts + "," + selectedItem.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="hosts_available"size="30" multiple="multiple">
<option value="1222">1.1.2.2</option>
<option value="1232">1.1.2.2</option>
<option value="1242">1.1.2.2</option>
<option value="1252">1.1.2.2</option>
</select>
<select id="hosts_assigned" size="30" multiple="multiple">
<option value="1111">1.1.2.1</option>
</select>
</form>
<button type="button" id="btnRight">>></i></button>
<br/>
<button type="button" id="btnLeft"><<</i></button>
<br/><br/>
<input type="text" id="hosts" />

You are getting more than one.
You need to loop. you also need to loop after removing
function getHosts() {
var current_hosts=[];
$("#hosts_assigned option").each(function() {
current_hosts.push($(this).val());
});
return current_hosts.length>0?current_hosts.join(","):"";
}
$("#btnLeft").click(function() {
$("#hosts_assigned option:selected").each(function() {
$("#hosts_available").append(this);
})
$("#hosts").val(getHosts());
});
$("#btnRight").click(function() {
$("#hosts_available option:selected").each(function() {
$("#hosts_assigned").append(this);
});
$("#hosts").val(getHosts());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="hosts_available" size="30" multiple="multiple">
<option value="1222">1.1.2.2</option>
<option value="1232">1.1.2.2</option>
<option value="1242">1.1.2.2</option>
<option value="1252">1.1.2.2</option>
</select>
<select id="hosts_assigned" size="30" multiple="multiple">
<option value="1111">1.1.2.1</option>
</select>
</form>
<button type="button" id="btnRight">>></i>
</button>
<br/>
<button type="button" id="btnLeft"><<</i>
</button>
<br/>
<br/>
<input type="text" id="hosts" value="" />

Related

How I can add data attribute into Hyperlink?

How to add multiple options from the selection box to the data attribute data-clc in the hyperlink?
Working in textarea but TestLink hyperlink not working.
$("#selection").change(function() {
$('#selected').html(' ');
$("#selection option:selected").each(function() {
var $this = $(this);
if ($this.length) {
var selText = $this.text();
console.log(selText);
$('#selected').append(selText + ', ');
$('#comeMan').attr('data-bid', selText);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="" style="width:200px;" id="selection" name="fm_fields[]">
<option value="90" selected>Collection1</option>
<option value="91" selected>Collection2</option>
<option value="92">Collection3</option>
<option value="93">Collection4</option>
<option value="94">Collection5</option>
<option value="95">Collection6</option>
</select>
<br/>
<br/>
<div>
TestLink
<textarea id="selected" rows="1" cols="50" readonly></textarea>
</div>
Goal
For example:
<a href="#"
id="comeMan" data-clc=" Collection2,Collection3,Collection4">TestLink</a>
Rather than build up a string of the selected items, you can just set the attribute to the value (val() in JQuery) of the select element.
Also, to more easily work with data- attributes, JQuery provides the .data() method (used below);
$("#selection").change(function() {
$('#comeMan').data('clc', $('#selection').val());
console.log( $('#comeMan').data('clc'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple style="width:200px;" id="selection" name="fm_fields[]">
<option value="90">Collection1</option>
<option value="91">Collection2</option>
<option value="92">Collection3</option>
<option value="93">Collection4</option>
<option value="94">Collection5</option>
<option value="95">Collection6</option>
</select>
<br/>
<br/>
<div>
TestLink
</div>

How to enable disable text input while making my function modular

Here is my script, what my goal is if other is selected in select, the other text input beside it will be enabled, this is what i've got so far, any approach will be really appreciated, I have 4 questions like this and I want it to be modular, best approach for doing my function to be reuseable.. How do I properly do this without any problem posting my data as 2 name inputs will generate 2 post variables in php.. T_T
<script type="text/javascript" charset="utf-8">
function validate()
{
var ddl = document.getElementById("cause_pain");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OTHER")
{
document.getElementsByClassName("causepain")[0].removeAttribute("name");
document.getElementsByClassName("causepain1")[0].removeAttribute("disabled");
}
}
</script>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain" onchange="validate()">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain" name="cause_pain" size="40" onkeyup="clean('this.id')" disabled>
<input type="submit" id="submit"/>
</form>
This method is reusable and pretty straight forward. Using data attributes, you could specify the element that needs to be shown on the specific option element. Also before showing any input element hide the elements that were attributed to the previous selection.
Example:
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER" data-show="cause_pain_other">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain_other" name="cause_pain" size="40"
onkeyup="clean('this.id')" disabled style="display: none;">
<input type="submit" id="submit"/>
</form>
<script type="text/javascript" charset="utf-8">
var selectedOpt;
function selectionChanged(e) {
if (selectedOpt && selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = true;
showEl.style.display = 'none';
}
selectedOpt = this.querySelector('[value="'+e.target.value+'"]');
if (selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = false;
showEl.style.display = 'block';
}
}
document.querySelector('select').addEventListener('change', selectionChanged);
</script>
Your selectedOpt should be an object if you're using multiple selects on the same page and then just add the element to the object with the id as an index:
var selectedOpt = {};
...
selectedOpt[this.id] = this.querySelector('[value="'+e.target.value+'"]');

How to show form input fields based on select value?

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();
}
});

Refreshing select after selected option is changed by jQuery

I'm updating the selected option programmatically using jQuery, but nothing changes in the browser. (That is, the old selected option remains selected instead of switching to the newly selected option.) Suggestions?
Thanks. --Jeff
I have a simple form like this:
<form id="form1" name="form1" method="" action="">
<p>Assign:
<select name="assigner" id="assigner">
<option value="Sam" selected="selected">Sam</option>
<option value="Harry">Harry</option>
<option value="Fred">Fred</option>
</select>
<input type="button" name="button1" id="button1" value="Submit" />
</p>
<p> Task A: <select name="assignment[]" id="assigner">
<option value="Sam">Sam</option>
<option value="Harry" selected="selected">Harry</option>
<option value="Fred">Fred</option>
</select>
</p>
<p>
Task B: <select name="assignment[]" id="assigner">
<option value="Sam">Sam</option>
<option value="Harry" selected="selected">Harry</option>
<option value="Fred">Fred</option>
</select>
</p>
</form></div>
and my jQuery code looks like this:
<script type="text/javascript">
jQuery(document).ready(function(){
$('[name="button1"]').click(
function(){
var form = $(this).parents('form');
var assigned = form.find(':selected').first().val();
form.find(':selected').each(function(index){
$(this).val( assigned ).change();
});
}
);
});
</script>
I'm updating the selected option programmatically using jQuery
Not as far as I can see. You're re-setting the value of the selected option, but not doing anything as far as I can tell to the actual select box.
To change a select box, you need to identify it, then call val on it, not one of its option elements.
I can't make out what you want your input[name="button1"] to do, but here's an example of updating a select box: Live copy | source
HTML:
<select id="theSelect">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type="button" id="theButton" value="Click me">
JavaScript:
jQuery(function($) {
$("#theButton").click(function() {
$("#theSelect").val("2");
});
});
Separately, as j08691 pointed out in the comments, you can't assign the same id value ("assigner") to more than one element. id values must be unique in the document. Your code doesn't show you using that id, so this may well be unrelated, but it's worth flagging up.
<form id="form1" name="form1" method="" action="">
<p>Assign:
<select name="assigner" id="assigner">
<option value="Sam" selected="selected">Sam</option>
<option value="Harry">Harry</option>
<option value="Fred">Fred</option>
</select>
<input type="button" name="button1" id="button1" value="Submit" />
</p>
<p>
Task A: <select name="assignment[]" id="assigner2">
<option value="Sam">Sam</option>
<option value="Harry" selected="selected">Harry</option>
<option value="Fred">Fred</option>
</select>
</p>
<p>
Task B: <select name="assignment[]" id="assigner3">
<option value="Sam">Sam</option>
<option value="Harry" selected="selected">Harry</option>
<option value="Fred">Fred</option>
</select>
</p>
</form>
<script type="text/javascript">
jQuery(document).ready(function(){
$('[name="button1"]').click(
function(){
var assigned = $("#assigner").val();
$('#form1 select').val( assigned );
}
);
});
</script>

JavaScript Populating an input Field Using an Html combo Box

i am trying to find a way to allow a user to click items in a combo box and have its value populate an input field and also alert "work stop" or "work start" message when appropriate option is selected. But my code is not working. Please Help!
Here is my code:
<html>
<head>
</head>
<body>
<form>
<select name="sel1" onChange="populateField(this.form)" >
<option value="">---Select---</option>
<option value="stop" >Stop</option>
<option value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script type="text/javascript">
function populateField(frm){
test = frm.stop.value;
alert('work' test);
frm.eStop.value = test;
}
</script>
</body>
</html>
Thanks in Advance
http://jsfiddle.net/snHQY/
<form>
<select name="sel1" id="select" onchange="populateField();" >
<option value="">---Select---</option>
<option name="stop" value="stop" >Stop</option>
<option name="start" value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script>
function populateField() {
test = document.getElementById('select').value;
alert(test);
document.getElementById('eStop').value = test;
}
</script>
You can do it using the selectedIndex if you want as well,
<form>
<select name="sel1" id="select" onchange="populateField(this);" >
<option value="">---Select---</option>
<option name="stop" value="stop" >Stop</option>
<option name="start" value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script>
function populateField(sel) {
sel.form.eStop.value = 'work ' + (sel.selectedIndex == 1 ? 'Stop' : 'Start');
}
</script>
http://jsfiddle.net/cnpuM/
Your code has two errors. You can not reference an element by its value like this test = frm.stop.value; instead use test = frm.sel1.value; . Another error is in this line alert('work' test);. Here you are joining a string "work" with a variable "test". In java script where ever you join two or more variables or strings and variables you alway have to join them with + sign like this:alert('work ' + test);. Remaining code is ok:
<html>
<head>
</head>
<body>
<form>
<select name="sel1" onChange="populateField(this.form)" >
<option value="">---Select---</option>
<option value="stop" >Stop</option>
<option value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script type="text/javascript">
function populateField(frm){
var test = frm.sel1.value;
alert('work '+ test);
frm.eStop.value = test;
}
</script>
</body>
</html>
You can also use selectedIndex property of "sel1" to do the same.
in your select you can add to onchange's and onkeypress to the populateField's function this as the objects reference.
<select name="sel1" onchange="populateField(this)" onkeypress="populateField(this)">
Now you can reference the select from o. to pass the selected value to the alert dialog and the input field.
function populateField(o){
alert("work " + o.value);
// use regular W3C DOM syntax for element referencing the input and populate it with the select objects selected options value
document.getElementById("eStop").value = o.value;
}

Categories

Resources