How to separate by pipe for multiple select in hidden field - javascript

I have a form that has 3 drop downs to make selections, the first drop down allows the user to select a specific Type, the second box, the user must select a date which will then present users with the filtered options on the 3rd drop down which is done in Jquery. I had it working where the user only selects one option in the 3rd drop down.
Now I would like the user to select multiple options. The code below is what I used to get the single selection to update the hidden field and pass via form submission.
The below code minus the ".join('|')" outputs the values into the hidden field then it gets passed into a data storage via POST.
This is my code:
$('#TopicID').on('change',function()
{ TIDval.val( $(this).find(':selected').text().join('|') );
});
I tried several versions to get it to work if I remove the ".join('|')" the output gives me all of the values concatenated.
Value 1: tree
Value 2: boat
Value 3: car
The output is as follows: treeboatcar
but I need: tree|boat|car
I have updated my new code to reflect the solution suggested by Loading... in this thread to the following.
$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');
$("#TopicID_value").text(selectedText);
});
Which now updates the hidden field value correctly with the pipe separated values but the value is no longer passed in the POST call when submitted in the form.
The hidden field
In firebug I see the value being updated properly when I select one or multiple options but for some reason the value gets lost in the submission process. I don't see much of a different where that could happen.

Use map()
$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');
console.log(selectedText);
});
$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');
console.log(selectedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="TopicID" multiple="true">
<option id="1">ABC</option>
<option id="2">XYZ</option>
<option id="3">PQR</option>
</select>

Related

How to keep values of select throughout the session

I have a table and i am adding new rows dynamically. Everything is working fine except my select.
I am able to hold all the values of my field except the select field.
So it is something like this When the user fills the form and click on initiate button, he is directed to second screen which is verification screen where he can verify the details and if wants to modify anything he can click on modify button and he will be redirected to first screen.
So the problem is the values filled by the user is retained in all the field but the value of the drop-down is not retained and is showing default value 'Select'.
Also i am able to get the selected value in array from 2nd to 1st screen and also i am able to assign the value to it but still its not displaying on the screen .Here's how.
Code
document.getElementById('fldsearch'+temp).options[document.getElementById('fldsearch'+temp).selectedIndex].value = arrsearch[temp];
arrsearch[temp] is an array where the selected value is stored.
fldsearch is the <td id> of select field.
temp is the increasing number of <td id> since i am adding rows dynamically.
Please do let me know if you need anything else.Thanks
First you have to set all values to drop-down. If all values are bind to select then one of them can be set to default value. Take a look at below example. Also please find fiddle link in comments.
<select name="ddlTitles" id="ddlTitles">
<option value="">Select</option>
</select>
$(function() {
var titles = ["Mr.","Ms.","Mrs.","Miss."];
for(var i=0;i<titles.length;i++){
var titleElement = document.getElementById("ddlTitles");
var option = document.createElement("option");
option.text = titles[i]
option.value = titles[i]
titleElement.add(option);
}
//Set default value to Ms.
$("#ddlTitles").val("Ms.");
});

Angular Select NgOptions double selecting when directive compiles

I am working on a dynamic form that populates a dropdown conditionally based on another input. I have written a directive because the data that comes back will also carry validation rules that need to be applied. However when i apply the validation rules to the dropdown and recompile the select options are borked. The final HTML looks like this:
The questions on the form can depend on another to be answered in a very specific way before they appear. This dropdown for example depends on the country selected but can be required or optional depending on what country is selected. The data coming back from my server gives me a validation object that contains validation information for the input field such as:
var question = scope.question;
var input = element.find('select');
if (question.validation.required) {
if (!input.attr('required')) {
input.attr('required', question.validation.required);
}
}
$compile(input)(scope);
The standard <option value="?" selected="selected"></option> is put in but when the question the dropdown depends on triggers the watch and a request happens for the dropdown the server returns and the backing select values are changed but the HTML output results as seen above all the items that are set to selected are unselectable and the form validation fails.
function answerMatch(countryCode) {
sectionService.getDivisionsByCountryCode(countryCode).then(function (response) {
scope.question.selectValues = response.data;
element.show();
});
}
and an HTML snippet for good measure
<select id="question{{question.questionId}}" name="answer" ng-model="question.value" ng-options="value.text for value in question.selectValues" class="form-control">
</select>

Basic java script to get combobox

I am just starting out with some java script in an asp.net mvc web site.
I current have a form which I am working on.
The first field which the user is prompted with is a combobox / select (in html)
here is the code for it:
<select name="select">
#foreach (var item in Model.networks)
{
<option value="">#Html.DisplayFor(modelItem => item.name)</option>
}
</select>
Now my next field depends on the option which they chose from the combo box.
How can I populate the next field based on the option they chose in the combo box?
So when the user navigates to the page they will ave a combo box populated with all the options. Below that will be empty fields. When the user selects a option in the combo box I want it to then populate the empty fields with the corresponding data from the option which was chosen.
How do I go about doing this?
Please give the newby answer as in the method in which it will be done. I am assuming that I will be using java script for it?
Although I cannot understand your question in detail, I hope I can help you.
HTML
If you have a select element that looks like this:
<select id=dropdown>
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Plain Javascript solution
Running this code:
var element = document.getElementByID('dropdown');
var current = e.options[e.selectedIndex].value;
Would make current be 2. If what you actually want is test2, then do this:
var e = document.getElementById('dropdown');
var strUser = e.options[e.selectedIndex].text;
Which would make current be test2
Put the onChange="getSelectedValue" attribute of the select element and then use the following javascript.
<script>
function getSelectedValue(sel)
{
txtToFill.Text(sel.options[sel.selectedIndex].text);
}
</SCRIPT>
If I understand your question correctly you want to react to a combo box value changing and display different content in your page.
If that is the case what you need to know is
how to handle the change event in the select (drop down)
populate empty fields
Here's how you can register and handle the change event in the dropdown:
$("select[name='select']").on("change", function(){
$('#input1').val("What you want in the input goes here");
});
Here's a fiddle that demonstrates this.

Is there a way to set `selected` flag instead of val() for dropdowns?

The select values are confusing me. When the user edits a row in my app I clone a tag with jquery (called empty-X) and put it on a modal window so that the user can edit the values. At the same time I get a json object (data) from server and fill in the current fields on the modal window as it stands in the database :
empty_X.find('#id_deals-1-currency').val(data[0].fields['currency']);
Now when the modal shows, the user can see how the correct currency is selected in the dropdown.
Yet when I check the HTML for this element with Firebug, I get a different picture, nothing seems selected.
<select id="id_deals-1-currency" name="deals-1-currency">
<option selected="selected" value="">---------</option>
<option value="1">USD - $</option>
<option value="2">EUR - €</option>
<option value="3">GBP - £</option>
</select>
And yet when I send the form to the server, there are no validation errors and the currency is the same value as it was previously set through val(). Life is good.
While this works by itself, there is a problem. What if the user wants to get back to the edit mode and verify the currency once more before saving it?
In this case I can't load the values from the database any more. His previous local changes matter now. I have to clone the current record with currency inside back in the modal window, so the user can see what he had changed previously and verify it. The problem is now the user doesn't see the currency he had changed in the previous step. In fact he would see an empty dropdown instead.
What are my options here? Is there a way to set the selected flag to the actual selection rather than using val()?
When cloning a <select>, the option with the 'selected' attribute becomes the current option in the cloned object - instead of the actual current object (as per value attribute).
To counter this, you can find the currently selected option from the value returned by val() and then apply the selected attribute to it prior to cloning it. This way you wont need to set the value after cloning.
Demo: http://jsfiddle.net/DqADq/
Code: (.x1 is the <select>)
// simple cloning
$('.x1:first').clone().appendTo('.out');
// setting selected attr before cloning
var v = $('.x1:first').val();
$('.x1:first option').removeAttr('selected'); // remove 'selected' from all options
$('.x1:first option').each(function() {
if($(this).attr('value') == v) {
$(this).attr('selected', true); // apply 'selected' to current option
}
});
$('.x1:first').clone().appendTo('.out');

Unable to select first element from select using Jquery

I am filling a drop down based on the value selected in the first drop down.Data being sent back from server is in JSON format and using JQuery to parse and fill the second select tag
<select name="abc" id="jobName">
<option value="-1">Please select a Job</option>
</select>
This is my Jquery code
var selectedGroup = document.getElementById(groupDropDownId);
var groupdata = selectedGroup.options[selectedGroup.selectedIndex].value;
var formInput='group='+groupdata;
$.getJSON('search/getSchedulerJobListForGroup',formInput,function(data) {
$('.result').html('' + data.jobList + '');
$.each(data.jobList,function(index, value){
var jobId = document.getElementById(resetDropDownId);
var option=new Option(value,value);
try{
jobId.add(option);
}
catch(e){
jobId.appendChild(option);
}
});
});
$("#jobName")[0].selectedIndex = 1;
// $("#jobName").val($("#triggerjobName option:first").val());
in above code groupDropDownId is ID of the drop down based on whose value, second drop down will be filled.resetDropDownId is ID of second drop down which i am trying to fill from JSON data getting from the server.
Upon filling the drop down, its also creating an empty option tag and it is getting select by default.
I am not sure if i can add some default value to that empty option so that i can select that default option value like "please select bla bla."
also i tried to select first element from the drop down but nothing seems working for me.I am wondering what i am doing wrong here?
Based on your question, it looks like you want to know how to change the value and text of an element within a dynamically populated select list.
Currently, you have this statement $("#jobName")[0].selectedIndex = 1; sitting outside of your getJSON request. If you move this inside of the getJSON function, it will work as expected.
If you want to set the value and text of that object, you'll want to use ->
$('#jobId option:first').val("Some Value").text("other stuff");
You can see a working JS Fiddle using dynamically populated select list from a JSON object.
Fiddle

Categories

Resources