Javascript/jquery write each text value from :selected option to separate input - javascript

I'm retrieving some data from MySQL and write it in certain select tags, then i retrieve every selected option value and display it in a DIV, here is the javascript:
function main() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div#one").text(str);
})
.trigger('change');
}
So, i want each retrieved value to be written in separate input:
First value: <input type="text" id="test" />
Second value: <input type="text" id="test2" />
Third value: <input type="text" id="test3" />
How can i do that? Many thanks!

Simple select always have a selected value, so you can try something like this:
$(function() {
$("select").change(function() {
var str = "";
$("select").each(function() {
str += $(this).val()+"<br/>";
});
$("div#one").html(str);
});
});
You can see in action here: http://jsfiddle.net/vJdUt/

For adding the selected options in a "div" tag:
//empty div at start using .empty()
$("select").change(function () {
//get the selected option's text and store it in map
var map = $("select :selected").map(function () {
var txt = $(this).text();
//do not add the value to map[] if the chosen value begins with "Select"
return txt.indexOf("Select") === -1 ? txt + " , " : "";
}).get();
//add it to div
$("#one").html(map);
});
For adding the selected options in an "input" tag:
//empty textboxes at start using .val("")
$("select").change(function () {
var text = $(":selected", this).text() //this.value;
//get the index of the select box chosen
var index = $(this).index();
//get the correct text box corresponding to chosen select
var $input = $("input[type=text]").eq(index);
//set the value for the input
$input.val(function () {
//do not add the value to text box if the chosen value begins with "Select"
return text.indexOf("Select") === -1 ? text : "";
});
});
Consolidated demo
http://jsfiddle.net/hungerpain/kaXjX/

Related

How to get the number of input tags containing certain text?

My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/

How to create a enhanced HTML TransferBox with an attribute

I need to create an enhanced transferbox, using HTML, JavaScript and JQuery.
I have a set of options a user can select from and associate with an attribute. The selection and deselection must be accomplished with two SELECT HTML elements (i.e., a transferbox). For example, these options can be a list of skill names.
When the 'add' button is clicked, the option(s) selected in the first SELECT element, along with an attribute (e.g. number of years from a text box) must be transferred from the source SELECT element to selected/destination SELECT element. The attribute must be displayed along with the item text in this second SELECT element (for example, the item displays the skill and the number of years).
When the 'remove' button is clicked, the selected option(s) in the second SELECT element must be moved back to the first SELECT element (in the original format .. without the attribute).
JSON should be the data format for initial selection setup and saving latest selections.
I want an initial set of selections and attributes to be set via JSON in an a hidden input field. I want the final set of selections to be saved to JSON in the same hidden input field.
Example HTML:
<input type="hidden" id="SelectionsId" value='[{ "id": "2", "attribute":"15"},{ "id": "4", "attribute":"3" }]' />
<!--<input type="hidden" id="SelectionsId" value='[]' />-->
<div>
<select class="MultiSelect" multiple="multiple" id="SelectFromId">
<option value="1">.NET</option>
<option value="2">C#</option>
<option value="3">SQL Server</option>
<option value="4">jQuery</option>
<option value="5">Oracle</option>
<option value="6">WPF</option>
</select>
<div style="float:left; margin-top:3%; padding:8px;">
<div>
<span>Years:</span>
<input id="YearsId" type="number" value="1" style="width:36px;" />
<button title="Add selected" id="includeBtnId">⇾</button>
</div>
<div style="text-align:center;margin-top:16%;">
<button title="Remove selected" id="removeBtnId">⇽</button>
</div>
</div>
<select class="MultiSelect" multiple="multiple" id="SelectToId"></select>
</div>
<div style="clear:both;"></div>
<div style="margin-top:40px;margin-left:200px;">
<button onclick="SaveFinalSelections();">Save</button>
</div>
Example CSS:
<style>
.MultiSelect {
width: 200px;
height: 200px;
float: left;
}
</style>
Visual of requirement:
Here's a solution to the challenge. The variables being setup at the start make this solution easy to configure and maintain.
When the page gets displayed, the SetupInitialSelections method looks at the JSON data in the hidden input field and populates the selected items.
When the 'Save' button clicked, the current selections are converted to JSON and placed back in the hidden input field.
Invisible character \u200C is introduced to delimit the item text and the attribute during display. This comes in to use if the item has to be removed and the original item text has to be determined so it can be placed back in the source SELECT element.
The selectNewItem variable can be set to true if you would like the newly added item to be selected soon after adding it to the SELECT element via the 'add' or 'remove' operations.
This solution supports multiple item selections. So multiple items can be added at once ... and similarly multiple items can be removed at once.
<script src="jquery-1.12.4.js"></script>
<script>
var savedSelectionsId = 'SelectionsId';
var fromElementId = 'SelectFromId';
var toElementId = 'SelectToId';
var includeButtonId = 'includeBtnId';
var removeButtonId = 'removeBtnId';
var extraElementId = 'YearsId';
var extraPrefix = " (";
var extraSuffix = " years)";
var noItemsToIncludeMessage = 'Select item(s) to include.';
var noItemsToRemoveMessage = 'Select item(s) to remove.';
var selectNewItem = false;
var hiddenSeparator = '\u200C'; // invisible seperator character
$(document).ready(function () {
SetupInitialSelections();
//when button clicked, include selected item(s)
$("#" + includeButtonId).click(function (e) {
var selectedOpts = $('#' + fromElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToIncludeMessage);
e.preventDefault();
return;
}
var attribute = $("#" + extraElementId).val();
selectedOpts.each(function () {
var newItem = $('<option>', { value: $(this).val(), text: $(this).text() + hiddenSeparator + extraPrefix + attribute + extraSuffix });
$('#' + toElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
//when button clicked, remove selected item(s)
$("#" + removeButtonId).click(function (e) {
var selectedOpts = $('#' + toElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToRemoveMessage);
e.preventDefault();
return;
}
selectedOpts.each(function () {
var textComponents = $(this).text().split(hiddenSeparator);
var textOnly = textComponents[0];
var newItem = $('<option>', { value: $(this).val(), text: textOnly });
$('#' + fromElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
});
// Setup/load initial selections
function SetupInitialSelections() {
var data = jQuery.parseJSON($("#" + savedSelectionsId).val());
$.each(data, function (id, item) {
var sourceItem = $("#" + fromElementId + " option[value='" + item.id + "']");
var newText = sourceItem.text() + hiddenSeparator + extraPrefix + item.attribute + extraSuffix;
$("#" + toElementId).append($("<option>", { value: sourceItem.val(), text: newText }));
sourceItem.remove();
});
}
// Save final selections
function SaveFinalSelections() {
var selectedItems = $("#" + toElementId + " option");
var values = $.map(selectedItems, function (option) {
var textComponents = option.text.split(hiddenSeparator);
var attribute = textComponents[1].substring(extraPrefix.length);
var attribute = attribute.substring(0, attribute.length - extraSuffix.length);
return '{"id":"' + option.value + '","attribute":"' + attribute + '"}';
});
$("#" + savedSelectionsId).val("[" + values + "]");
}
</script>

How to change the function to limit its action to the id, class or selector

I have a function written in jquery that copies the value of the checkbox to the textarea #msg
$(document).ready(function(){
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Clicking any checkbox on side copies of its value to the #msg field
How to reduce this effect that only checkboxes in the <ul> or a selected div operate in such a manner?
I want this:
<ul>
<input name="foo2" type="checkbox" value="Hello" id="tel_1">
<label for="tel_1">Hello</label>
</ul>
To be copied to the #msg textarea and this :
<input name="foo" value="123123123" id="tel_11" type="checkbox">
<label for="tel_11">Alan</label>
Not to be copied. I played with this :
$("input:checkbox").click(function()
And changed input:checkbox to ul:input:checkbox but I do not want to work.
You could use the id :
$(document).ready(function(){
$("#tel_1").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Or if you want to exclude just #tel_11 you could use :not() selector like :
$(document).ready(function(){
$("input:checkbox:not('#tel_11')").click(function() {
var output = "";
$("input:checked:not('#tel_11')").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Update :
If you have several id's as you sain in the comment (answers example) you could use start with selector like $("[id^='answer_'") ans that will include all of your 18 answers, e.g :
$(document).ready(function(){
$("[id^='answer_'").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Hope this helps.
Use a selector that just matches checkboxes that are children of <ul>.
$("ul > :checkbox").click(function() {
...
});

jquery - identify items by class and then extract value

I have the following hidden input field on my form:
<input class="dow" id="hidden_dow0" type="hidden" value="m,t,w,r,f,s,n">
Once the form has loaded I need to find this hidden control, extract the value... and then use each item in the list ('m,t,w ') to set corresponding checkboxes on
So far, I have been able to find all hidden inputs, but I don't know how to extract the value from it.
Here's what I have so far:
$('.dow ').each(function (i, row) {
var $row = $(row);
var $ext = $row.find('input[value*=""]');
console.log($ext.val); //fails.
});
EDIT 1
This is I tried:
//find all items that have class "dow" ... and
$('.dow ').each(function (i, row) {
var $row = $(row);
console.log(i);
console.log(row); //prints the <input> control
//var $ext = $row.find('input[value*=""]');
var $ext = $row.find('input[type="hidden"]');
console.log($ext); //prints an object
$ext.each(function() {
console.log( $(this).val() ); //does not work
});
});
In jQuery val() is a function.
The .dow element is the input, you don't need to find it
$('.dow ').each(function (i, row) {
console.log( $(this).val() ); //works
});

How can I extract the values entered in the input boxes generated dynamically and pass it to controller using jquery?

I have a form wherein a user can enter input boxes and remove them at a click. I want to extract the values entered in these input boxes and pass them to controller using jQuery. How do I do that?Right now I am using ids to extract the values but I do not think that is a better method because suppose I add 4 options and then I remove all of them and then again add inputs, I will not be able to track these ids and extract the values.
Here is my HTML code:
<button type="button" class="addoption" id="addoption_btn">Add more option</button>
<div id="Options">
<input type="text" name="mytext[]" id="option_1" placeholder="Option 1"/>
</div>
Here is my JavaScript:
var MaxOptions = 4; //maximum input boxes allowed
var Optionsform = $("#Options"); //Input boxes wrapper ID
var AddButton = $("#addoption_btn"); //Add button ID
var x = Optionsform.length; //initial text box count
var OptionCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxOptions) //max input box allowed
{
OptionCount++; //text box added increment
//add input box
$(Optionsform).append('<div><input type="text" name="mytext[]" id="option_'+ OptionCount +'" placeholder="Option '+ OptionCount +'"/>×</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
});
Here is the jQuery I am using to pass the data to my controller:
$("#addquestion_btn").click(function(){
var val= CKEDITOR.instances['question_topic'].getData();
storequestion(val);
});
function storequestion(ques)
{
$.post("/instructor/store/question",{
question: ques,
option1: $("#option_1").val(),
option2: $("#option_2").val()
},function(data){
if(data[0]==="success")
{
window.location.href = '/instructor/create/topics';
}
else
{
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}}
,'json');
}
Please use below mentioned code to read through all displayed options.
function storequestion(ques) {
obj = {};
obj[question] = ques;
$("#Options:input[name*='mytext']").each(function (index) {
obj['option' + index] = $(this).val();
});
$.post("/instructor/store/question", obj
, function (data) {
if (data[0] === "success") {
window.location.href = '/instructor/create/topics';
}
else {
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}
}
, 'json');
}

Categories