Adding more than one value to text box - javascript

I'm trying to allow users to add a list of 'favourites' to a text box but when adding more than one value it replaces the value already there. Can anybody help? Thanks this is my code:
var name
function getFavourite() {
name = "Student 1, ";
$('#output').val(name)
saveFavourites();
}
function getFavourite2() {
name = "Student 2, ";
$('#output').val(name)
saveFavourites();
}
function saveFavourites() {
var fav = $("#output").val();
if (fav !== "") {
localStorage[name] = $("#output").val();
$("#output").val(name);
}
}
function loadFavourites() {
var fav = $("#name").val();
if (name !== "") {
$("#output").val(localStorage[name]);
$("#name").val("");
}
}

using val will replace the existing value as you already noticed so i would do something like this if you want to add to that value.
$("#output").val($("#output").val() + ', ' + name);
At least if i understand you correctly. This would get the excising value and then add the new value to it (in this case with a comma but is not necessary)
Of course if you need the same element twice or more is better to assign it to a var instead of calling the selector twice.

I think you are looking into multiple select dropdown, something like this:
http://codepen.io/martynasb/pen/kawxq

You don't an text input, you want a select where you can select multiple values. In html, it's <select multiple>.
The plugin I know that provides the best experience for this is is Select2: http://ivaynberg.github.io/select2/#basics
And you don't have to load all the options right away, they can be fetched via ajax easily.

Related

How to serialize just one value of input via jQuery?

I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?

Preserving quotes in jquery string

I'm creating options of a dropdown using jquery. User will enter the option text in the textbox keyvalue and on keyup() it will be added to <select>.
Eg: If user enter string Size , an option will be added in the dropdown like
<option value="Size">Size</option>
HTML
<input type="text" id="keyvalue" onkeyup="addvaluetoselect()">
<select id="key"></select>
jQuery
var keyvalue = $('#keyvalue').val();
if ($("#key option[value='"+keyvalue +"']").length == 0)
$('#key').append('<option value="'+keyvalue +'">'+keyvalue +'</option>');
If user types a value including double or single quotes, it should be added to the option. But currently it is not working. I tried by adding
var keyvalue = keyvalue .replace(/(['"])/g, "\\$1");
to escape the quotes. But when I try to enter a option Size's , the option is getting created like Size/'s instead of Size's.
Can anyone help me to fix this. Thanks in advance.
Don't append this as raw string, build it properly instead:
var keyvalue = $('#keyvalue').val();
var exists = $('#key option').map(function() {
return $(this).val();
}).toArray().indexOf(keyvalue) >= 0;
if (!exists) {
var newOption = $("<option></option>");
newOption.attr("value", keyvalue);
newOption.text(keyvalue);
$('#key').append(newOption);
}
As you can see, the check to see if the value already exists was also wrong, fixed that by iterating the existing options and checking their value against the value typed by the user.

Disable Drop-down list item without removing the value from FormCollection

I have a number of the following drop-down lists within this page, each with a list of selectable users. When a user is selected in one list, I don't want them to be selected in any further lists. For this reason I have written a script to disable them.
When the form is submitted, the username of each user selected in a drop-down list should be appended to the Uservalue in the Form Collection.
This works correctly without the disabling of names but when I add seat-selectinto the class description, the names are always returned in the FormCollection as empty strings.
Do you know why this is or what I can do to keep the names populating correctly in the FormCollection?
Drop-Down List:
#Html.DropDownListFor(m => m.User, Model.UserList, "Select User", new { #class = "form-control seat-select", #id = "uniqueID", #onchange = "cleanUsers(this);" })
Java Script:
function cleanUsers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) { $(".seat-select option[value='" + val + "']").attr("disabled", true); }
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
UPDATE 06/06/2016:
Apologies to bring back an old post. I have tried the advice listed below and this works to return one of the selected values. Unfortunately, In my solution I have a number of identical drop-down lists and I need to keep track of exactly which result is from which drop-down.
I have posted my new code below. The string is overwritten when each of the drop-down menus is changed so does not currently work for me.
New JavaScript:
function cleanRowers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) {
$("#SelectedUserText").val(val);
$(".seat-select option[value='" + val + "']").attr("disabled", true);
}
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
The Hidden value being updated:
#Html.HiddenFor(m => m.SelectedUserText)
I am trying to make the code as re-usable as possible so dont really want a different identifier for each of the drop-downs but it is important that I keep track of which drop-down the information is coming from.
Is there a way in which this can be done?
Disabled attribute do not put value in form submission thats why you are receiving empty string .
Here is a trick you can apply :
Put the selected value in a hidden input field onchnage function then read the hidden value on form submission instead of reading vslue of disabled dropdown.
Hope that helps .

HTML select onChange doesnt work

I am not any kind of proficient in JavaScript.
So I wrote a simple function to use on HTML SELECT, but it doesn't work.
JavaScript:
<script type="text/javascript" language="JavaScript">
function changeFormAction() {
var value = document.getElementById("format");
if (value == "freeText") {
document.getElementById("regularExpression").setAttribute("disabled", false);
}
}
</script>
HTML:
<select id="format" name="customFieldType" onChange='changeFormAction()'>
...
</select>
<input id="regularExpression" type=text size=5 name="format" disabled="true">
Any help will be highly appreciated
value in your code contains the element "format". Usually, to get the value, you just add .value as suffix. But since this a select/dropdown you'll have to do:
var element = document.getElementById("format");
var value = element.options[element.selectedIndex].value;
var text = element.options[element.selectedIndex].text;
Now value and text will contain the different strings like below:
<option value="thisIsTheValue">thisIsTheText</option>
Use either to compare with. I'll use both below to show as an example:
function changeFormAction() {
var element = document.getElementById("format");
var sValue = element.options[element.selectedIndex].value;
var sText = element.options[element.selectedIndex].text;
if (sValue == "freeText" || sText == "freeText") {
document.getElementById("regularExpression").removeAttribute("disabled");
}
}
The issue is something else.. It does hit changeFormAction function on change of customField select list..
var value = document.getElementById("regularExpression");
is wrong usage..
you should use it as
var value = document.getElementById("regularExpression").value
And adding from comments for disabling it also can be
document.getElementById("regularExpression").removeAttribute("disabled");
This wont work because you are trying to fetch text box value using document.getElementById("regularExpression").value;
But on page load you are not having any thing as default value in text box
You might be needed to fetch value of select box.
I think you need something like this:
http://jsfiddle.net/ew5cwnts/2/
function changeFormAction(value) {
if (value == "freeText") {
document.getElementById("regularExpression").removeAttribute("disabled");
}
}
HTML:
<select name="customFieldType" onchange='changeFormAction(this.value)'>

How to insert text into an array based upon keywords with JQuery

Within a web project I am using jQuery and javascript to build a query string for a user to use within a search tool. Since this is built on the fly by the user I take the fields and the values from the form and then add this to an array which is then pushed over to the search term in the ui.
Prior to passing this string to the UI I would like to format the string based upon keywords. (Example if the keyword BETWEEN all caps) is used in the query wrap the input fields following this keyword (there will be two) in parentheses. If the term CONTAINS is used wrap the succeeding field with asterisk and so on. Within JavaScript there is function for slice which allows me to insert text at an index within an array. Since I am looking for keywords within the array and not index values is there another function or approach that would support this.
below is the code for the creation/parsing of the input fields into the search term
//insert field after between option or remove it if it exists
function insertFromField(param1, param2, param3) {
if (param1 == "BETWEEN") {
$("<input class='queryterm' type='text'name='fieldValue1' id='fieldvalue1' value='' size='15' /><span> TO </span>").insertAfter(param2);
}
if (param3 <= 2) {
// do nothing
}
else {
$(param2).next().remove();
$(param2).next().remove();
}
}
//build query string from Query Builder //TODO formatting on string return
function setQueryString() {
checkField();
var txt = $("input[name='tbsearchterm']");
var fields = $("#queryFields :input").serializeArray();
jQuery.each(fields, function (i, field) {
if (txt) {
txt.val(txt.val() + field.value + " ");
}
});
}
//the UI contains an add button so the user can build their query at runtime for that i have the following:
$('#add').click(function () {
$("<div class='additionalrow'><select class='queryterm' name='condition'><option value='AND'>AND</option><option value='OR'>OR</option></select> "+
"<select class='queryterm' name='condition'>" +
"<option value='address:'>Address</option>" +
"<option value='age:'>Age</option>" +
... edited for Brevity
"</select> <select name='operator'class='operClass'><option id='opt1'>Equals</option><option id='opt1' value='CONTAINS'>Contains</option><option id='opt2' value='DOES NOT CONTAIN'>Does Not Contain</option><option id='opt3' value='LIKE'>Like</option><option id='opt4' value='BETWEEN'>Between</option></select> <input type='text' class='queryterm' name='fieldValue1' id='fieldvalue1' value='' size='25' /> <a href='#' id='btnRemove'><span class='advButtons'>Remove</span></a></div>").appendTo('#queryFields');
});
Thanks in advance
Update to comments
Thanks for the reply for more clarification:
1. I am hoping to accomplish this preferably using jQuery but I am not opposed to using javascript if jQuery does not contain functions that support this in.
2 & 3. Contains will always have one value . Where contains will always have two. The function insertFromField is called when the selection is changed on the selector drop down menu
A full working sample can be viewed here jsFiddle
When you change the second selector you will see the additional input field added. This is triggered by the insertFromField function. This basically evaluates the entire div element and counts the number of input fields and adds or removes one accordingly.
I have also added some code to allow you to view the result in the UI.
The intended output would be when the word BETWEEN is used place parentheses around the values of the last two input field
so it would look something like this: AND Address 123 main street BETWEEN (17 18)
Sorry for not thinking of Fiddle earlier
Here ya go:
function setQueryString() {
checkField();
var txt = $("input[name='tbsearchterm']");
var hit_between=0;
var hit_contains=false;
var ops={
normal: ["" ," " ]
,contains:["*","* "]
,between1:["("," " ]
,between2:[" ",") "]
}
if (txt) {
jQuery.each(fields, function (i, field) {
var v=field.value;
if (false) {
}else if (v=="CONTAINS") {
if (hit_contains==false) {hit_contains=true;return;
}else{
//bad input; do something
}
}else if (v=="BETWEEEN"){
if (hit_between==0) {hit_between++;return;
}else{
//bad input; do something
}
}else{
var op='normal';
if (false) {
}else if (hit_contains) {hit_contains=false;op='contains';
}else if (hit_between==1){hit_between++; op='between1';
}else if (hit_between==2){hit_between=0; op='between2';
}else{
}
var nv=ops[op][0]+v+ops[op][1];
txt.val(txt.val() +nv);
}
});
}
}
Javascripts replace() function can search a string by regular expression
an has a function callback if a match is found. Now You need a regular expression describing the search terms.

Categories