Preserving quotes in jquery string - javascript

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.

Related

Why can't I select this input field using this regex filter in jQuery?

So I'm using padolsey's regex filter to try and select dynamically generated nested form fields. Why do I keep getting an empty value for test in the selector code below?
jQuery.expr[':'].regex = function(elem, index, match) {
var matchParams = match[3].split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels,'')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g,''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
//selector code
$(document).ready(function() {
var test = $('input:regex(id, agreement_activities_attributes_\d*_id)');
console.log(test);
});
html code that contains input field I'm trying to select
<input id="agreement_activities_attributes_0_id" name="agreement[activities_attributes][0][id]" type="hidden" value="28" />
There is an error in the code.
.replace(/^s+|s+$/g,'')
should be
.replace(/^\s+|\s+$/g,'')
Then it should work.
The replacement removes any surrounding whitespace (trims the string). The space you used in the selector (:regex(id, agreement_activities_attributes_\d*_id)) would be included in the match pattern, and thus only match elements with an id that started with space.

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)'>

Adding more than one value to text box

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.

how to save sorting order in select2() field?

I'm using select2() field using select2 library and Drag and Drop Sorting is enabled in the field.
It works well, but once i save it, the ordering break and they are ordered alphabetically.
I was wondering if its possible to anyhow save ordering of elements after drag drop in select2() fields.
Please suggest.
Per Select2 documentation, the new ordered values are saved in a attached hidden field.
http://ivaynberg.github.io/select2/
(right click on the Input field and then inspect element to find the line below just after the div#select2-container)
There are two options that might work for you:
Option 1:Easy one
Check the ordering of how you are feeding the control, specific on:
$("#e15").select2({tags:["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"]});
The control just render the same order that the above line is specified.
If you are not saving those values as comma separated text and instead as row records, maybe your database query is ordering them alphabetically.
Option 2: A little bit further
This code will serve you to save the ordered values in a cookie, so you can have the same order within your whole session.
$(function(){
if ($.cookie('OrderedItemList') != null){
$("#e15").select2({tags: $.cookie('OrderedItemList').split(',')});
}
$("#e15").on("change", function() {
$("#e15_val").html($("#e15").val());
$.cookie('OrderedItemList', $("#e15").val(), { expires: 365 });
});
});
Please note, this code might not work for database bound fields, you might need to add some code if thats what you need.
Well I had your problem. I've overcome it with something like this...
A hidden input to save your order.
the listener on the select2.
$("#reports").on('change', function(){
var data = $(this).select2('data');
var array = [];
$.each(data, function(index, val) {
array[index]=val.id;
});
array.join(',');
$("input[name=reports]").val( array );
});
<form class="form-horizontal form-bordered" action="#something" method="post" accept-charset="utf-8" target="_blank" >
<input type="text" name="reports" >
<select id="reports" class="form-control select2me" multiple >
<? foreach ($Balance::getSeparators() as $key => $value ) { ?>
<option value="<?=( $key )?>"><?=( $value )?></option>
<? } ?>
</select>
</form>
This way the input[name=reports] sends to your page the correct order.
Select2 has progressed to version 4, which is based on <select/> and <option/>-tags, instead of <input/>-tags. I solved it for version 4 as follows:
$(".select2").select2().on('select2:select', function(e){
var $selectedElement = $(e.params.data.element);
var $selectedElementOptgroup = $selectedElement.parent("optgroup");
if ($selectedElementOptgroup.length > 0) {
$selectedElement.data("select2-originaloptgroup", $selectedElementOptgroup);
}
$selectedElement.detach().appendTo($(e.target));
$(e.target).trigger('change');
})
Basically I remove and re-add the selected items to the select-options-list, so that they appear in order of selection.
The hidden field solution was a good solution in my case, but Select2 plugin still keep a numerical/alphabetical(?) order, that is not the user selection's order
I found a solution, that solves all my needs.
In my symfony form declaration will be the hidden field called selectOrder in which to save the current order:
$("#form_people").on('change', function(){
var data = $(this).select2('data');
var array = [];
$.each(data, function(index, val) {
array[index]=val.id;
});
array.join(',');
$("#selectOrder").val( array );
});
and in the javascript part after form declaration there is my Multi Select2:
var sel = $("#form_people").select2({
maximumSelectionSize: 3,
minimumInputLength: 1,
escapeMarkup: function(m) { return m; },
});
then
//After reloading page you must reselect the element with the
//right previous saved order
var order = $("#selectOrder").val().split(",");
var choices = [];
for (i = 0; i < order.length; i++) {
var option = $('#form_people option[value="' +order[i]+ '"]');
choices[i] = {id:order[i], text:option[0].label, element: option};
}
sel.select2('data', choices);
It's what I need, and maybe can help other developers

How to assign array variable to select box dropdown options?

I have a form which is largely populated by checkboxes. The checkboxes each have an ID "value" that corresponds to an item within a javascript array. The array items hold some text that will populate a textarea.
I would like to include some dropdown boxes to clean up the site; however, I cannot seem to assign an array ID to the dropdown options? Can this be done in a selectbox option? Is there a workaround to simulate a selectbox without using the tab?
My html is basically:
<div>
<input type=checkbox id=array1 name=textArray></input>
<input type=checkbox id=array1 name=textArray></input>
<input type=checkbox id=array1 name=textArray></input>
...
<select><option 1><option 2>...</select>
</div>
<div>
<form>
<textarea id=outPut></textarea>
</form>
</div>
And my js is:
var textArray = {
array1: 'some text here',
array2: 'some more text',
array3: 'some other text',
...
array90: 'the last text'
};
// variable assigned to chosen item
var selectedInputs = document.getElementsByName("textArray");
for (var i = 0; i < selectedInputs.length; i++) {
selectedInputs[i].onchange = function() {
chosenItem = this;
printText();
};
}
// Script to add items to the Comments section text area
var mytextbox = document.getElementById('outPut');
var chosenItem = null;
function printText(){
if(chosenItem !== null){
mytextbox.value += textArray[chosenItem.id] + "";
// resets the radio box values after output is displayed
chosenItem.checked = false;
// resets these variables to the null state
chosenItem = null;
}
}
How can I associate an item in my js array with one of the selectbox choices?
I found it very difficult to understand what you're asking but I threw this together and hopefully it'll be helpful.
Important bit is
var selectNode = document.getElementById('select'); // <select id="select">
selectNode.onchange = function () {
if (selectNode.selectedIndex !== 0) {
chosenItem = selectNode.options[selectNode.selectedIndex];
selectNode.selectedIndex = 0;
printText();
}
}
and not to use the id attribute for what you're doing (I used data-i).
I'd also like to say that if you're cleaning up code this would be a good time to strongly reconsider how you're passing variables between functions; setting a value in the global namespace and relying on it in the next invocation is just asking for trouble (race conditions, conflicts with other bits of code, etc).
<option value="whatever">1</option> This has been part of HTML from the beginning.

Categories