I am trying to add comma separated values to a hidden form field for later processing using the change of a dropdown menu as my trigger.
$("#artistselect").change(function() {
var allids = [];
allids.push($(this).children(":selected").attr("id"));
$("input[name=artistslist]").attr("value", $(allids).append(allids + ", "));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="artistselect">
<option value="1">1</option>
<option value="1">1</option>
<option value="1">1</option>
</select>
<input type="hidden" name="artistslist" value="" />
</form>
Best I can manage is to get the value to change to the selected dropdown, but it wont add them together with the commas.
Move var allids=[]; out of the event because you're destroying it every time it fires.
var allids=[];
$("#artistselect").change(function() {
allids.push($(this).children(":selected").attr("id"));
$("input[name=artistslist]").val(allids.join(', '));
});
On the last line you can use Array.prototype.join to get a comma separated string from the array.
Not sure why you are using .attr("id") when your html shows your options with no id attribute. Looks like you want value not id.
You have two problems.
First, you're emptying allids every time the user selects from the menu. So when you push onto it, you lose the old values, and you just get the most recent value.
Second, $(allids).append(allids + ", ") doesn't do what you think it does. .append() is for adding something to a DOM element, not concatenating strings.
To get the value of a <select>, just use $(this).val(), you don't need to search for :selected. Your <option> elements don't have IDs, so .attr('id') won't return anything.
var allids = [];
$("#artistselect").change(function() {
allids.push($(this).val());
$("input[name=artistslist]").val(allids.join(", "));
});
$("#show").click(function() {
console.log($("input[name=artistslist]").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="artistselect">
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="artistslist" value="" />
<button type="button" id="show">Show hidden value</button>
</form>
Related
I have a drop list where the nurse choose from, a diagnostic, and then this diagnostic is added into a textarea where the nurse will add more details near it. Then, they can add more diagnostics into the same textarea and add more info near this diagnostic.
Whenever the nurse selecting diagnostics, they are adding normally, but the moment she types in the textarea near the diagnostic added, and went to add another one, nothing is added.
Here is the jQuery script for the process:
$("#medication_id").on('change', function(){
$("#medication_pill").text($("#medication_pill").text() + " + " + $("#medication_id option:selected").text());
});
Change your code to use $("#medication_pill").val(). This will work for you:
$("#medication_id").on('change', function(){
$("#medication_pill").val($("#medication_pill").val() + " + " + $("#medication_id option:selected").text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='medication_id'>
<option>Medication 1</option>
<option>Medication 2</option>
<option>Medication 3</option>
</select>
<textarea id="medication_pill"></textarea>
The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.
It is hard to debug without html code. So please always remember that when you ask a question you should add enough code so that the problem was reproducable.
This code has a few things that should be changed
First of all avoid using $(selector) more than it is necessary (it is memory consuming). If you want to perform a couple of operations like in your case on an element $("#medication_pill") just save it to a variable.
Secondly on html form elements it is better to use val() function instead of text(). Here is why
Lastly in an change event you do not have to do make jQuery call to the select element ($("#medication_id option:selected")) since this event is bounded to this element. Instead you can just use $(this).
Here is an working example with desired functionality.
$("#medication_id").on('change', function() {
var textarea = $("#medication_pill");
textarea.val($("#medication_pill").val() + " + " + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="medication_id">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<textarea id="medication_pill"></textarea>
And here is an example with clearing select after change so that you can select tha same option couple of times in a row.
var select = $("#medication_id");
var textarea = $("#medication_pill");
select.on('change', function() {
textarea.val($("#medication_pill").val() + " + " + select.val());
select.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="medication_id">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<textarea id="medication_pill"></textarea>
I am using laravel, and trying to integrate some jquery, which I am not very good at.
I have a multiple select box with potentially lots of options, based on database values.
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
The user can select tools directly from the select box, but this can be a huge list and therefore I am also displaying a search field below the select box to
search the database of tools so the user can see more info about the tool, and then decide if he wants to include it.
Currently the user has to first search, then find the entry in the select box and select it.
I want a faster solution with a button next to the info about the tool, that automatically adds selected="selected" to the correct option in the select box above.
I tried
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$("div.toolselect select").val(id);
}
But that erased all the other other selected fields.
Any ideas would be appreciated.
Try using jQuery's prop function:
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$('.toolselect select option[value="'+ id +'"]').prop('selected');
}
</script>
For a multi-select, the value is an array of all the selected items. You're just setting the value to a single item, which is treated as an array of one element, so all the other selections get discarded.
So you should get the old value, add the new ID to it, and then set that as the new value.
function addselect(id) {
$('.toolselect select').val(function(i, oldval) {
oldval = oldval || []; // oldval = null when nothing is selected
oldval.push(id);
return oldval;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
<input type="button" value="Select 1" onclick="addselect('1')"/>
<input type="button" value="Select 2" onclick="addselect('2')"/>
<input type="button" value="Select 3" onclick="addselect('3')"/>
Instead of using this :
addselect = function (id){
$("div.toolselect select").val(id);
}
Try this :
addselect = function(id) {
var temp = [];
var arr = $('select').val();
for(i=0;i<arr.length;i++){
temp.push(arr[i]);
}
temp.push(id);
$("div.toolselect select").val(temp);
}
This way your previous selection is preserved, and the new selection is appended to the previous selection.
Hope this helps.
I'm trying to use Select2 (https://select2.github.io) to allow a user to type multiple tags into a field before submitting a form. In my Laravel PHP app, I'll then take those tags, determine if they exist and add them into a database.
My problem is that I can't seem to get Select2 to recognise there are multiple tags being entered by the user. When I interrogate the form data, I only see the LAST tag a user typed as opposed to ALL the tags.
My Select2 element is:
<select class="tags-field" name="tags" data-tags="true" data-placeholder="TAGS" multiple="multiple">
</select>
and my JQuery is:
$(function() {
$(".tags-field").select2({
maximumSelectionLength: 3,
tokenSeparators: [','],
});
}
There are no Javascript errors and it works perfectly fine except I cannot detect ALL the tags.
To cause PHP to make all the selected choices available as an array, suffix your select name with a pair of square brackets, like this:
<select class="tags-field" name="tags[]" data-tags="true" data-placeholder="TAGS" multiple="multiple">
If this form is sent to a PHP program, the value of $_POST['tags'] will be an array. Note that the square brackets in the form control name aren't a part of the array key. You would process such a form like this:
<?php
$tags = $_POST['tags'];
// Note that $tags will be an array.
foreach ($tags as $t) {
echo "$t<br />";
}
?>
References here: http://bbrown.kennesaw.edu/papers/php2.html
use hidden input field in order to send all values
use onsubmit event to set the value of the hidden field
HTML:
<form method="post" action="post.php">
<select multiple id="e1" style="width:300px" name="_state">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<input type="hidden" name="state" value="" />
<input type="submit"/>
</form>
JQ:
$("#e1").select2();
$('form').submit(function () {
var newvalue = '';
var value = $('select[name="_state"]').val();
if (value) {
newvalue = value;
}
$('input[name="state"]').val(newvalue);
})
Select numbers (you can select each number any number of times):
<select name="number_selection" method="post" id="number_selection" >
<option value="0">0</option>
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="button" value="Select" id="select_button"/>
<div id="feedback"> </div>
what I've tried in jquery is this....
$('#select_button').click(function(){
var gs= $('#number_selection').val();
$('#feedback').html(gs);
});
Now, What i am trying to do is, if i select a number from the options, it should display in the 'div' and if i select another number or the same number again, it should display beside the first number, but i am only able to select only a single number, not multiple numbers. I want the do this using jquery
If you don't understand my problem, i can explain you further. Please help.
And also if I want to deselect each element from the list appended?
I've tried this... but isn't working.
$('#select_button').click(function(){
var gs= $('#number_selection').val();
$('#feedback').append(gs + ' ' + '<input type="button" value="Remove" id="gs_remove" />' + '<br>');
});
$('#gs_remove').click(function(){
(this).hide();
});
but with this i am not able to remove each selected option.
Replace
$('#fcb_pt_gs').html(gs);
by
$('#fcb_pt_gs').append(gs);
$('#select_button').click(function() {
var _val = $('#fcb_pt_gs').text();
var gs= $('#number_selection').val();
if( _val == "" ) {
var _collection = [];
}
else {
// Add in collection
var _collection = [_val];
}
_collection.push( gs );
$('#fcb_pt_gs').html( _collection.join(',') );
});
Having this fieldset:
<fieldset>
<legend>[*death]</legend>
<select name=death style="width: 120px">
<option value=Dead>[*died]
<option value=NotDead>[*alive]
<option value="" selected>-
</select>
</fieldset>
i want to set the [2].value to "-".
i have tried without any success:
document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';
Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?
Thanks
[EDIT] of course, appropriate fieldset is:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
thanks.
It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?
document.getElementsByName('death')[0].selectedIndex = 2;
Or, are you asking to change the value of option at index 2?
var d = document.getElementsByName('death')[0];
d.options[2].value = '-';
You need to manipulate the selected property of your select object, try
document.getElementsByName('death')[0].selectedIndex = 1;
In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".
Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
you can do this using jQuery... it's easy...
j("#death").val(2)
document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...
Here's an alert example of how to access your specific option values with getElementsByName
alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead