i have to create an input with line break inside.
Attempted to do like this, (using Choices.js library for multiple autocomplete tag) :
<select id="choices1" class="form-control" name="choices-multiple-remove-button" placeholder="Compétences" multiple>
js:
arrayOfObjects.forEach(function(obj){
var options = '<option value="' + obj.id + '">' + obj.name + '\n' + obj.description +'</option>';
choices1.insertAdjacentHTML('beforeend',options);
});
As you can see, i want to have the description under the name line.
Is it impossible to create a hack in order to have '\n' or something else works ?
Related
I am trying to delete select box using jQuery remove function but it does not work. The select box itself is dynamically generated one. I want to delete the same select box if the user wants to delete the dropdown after adding. My code is:
$("#dltElement").click(function() {
$("#idSelect").remove();
});
My code to add the select boxes:
$(document).ready(function() {
var count = 3;
$("#btnCompare").click(function() {
if (count > 4) {
alert("Only 4 options are allowed");
return false;
}
$("#form-group").append(
"<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
"<option>--Select Product" + counter + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />'
);
count++;
}); // Script for adding dropdown dynamically
});
#idSelect is not present you have to use #idSelect0 or #idSelect1 ... and so on. Rather than you can lookup the events using event delegation on your #form-group to delete the closest element select closest to your input button or in your case your sibling select. This ~ is a sibling selector and will select the sibling select.
A good idea would be to add a class to your select and use that instead as we have used your class .btn-minus for listening to click events, (in case if you have more than one select all will be selected)
$("form-group").on('click', '.btn-minus' , function() {
$(this).find('~select').remove();
});
Find the sibling select and remove
Edit 2
I have added a snippet using .closest() You can check it out. Closest will try to locate the parent div with class container and remove the select and the minus button
$(document).ready(function() {
$("#form-group").on('click', '.btn-minus' , function() {
$(this).closest('.container').remove();
});
$("#btnCompare").click(function() {
var count = $("#form-group > div.container").length;
if (count >= 4) {
alert("Only 4 options are allowed");
return false;
}
//you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button
var label = $("#form-group > div.container").last().data('id')*1+1;
$("#form-group").append(
"<div class=container data-id="+label+"><select name='idSelect" + label + "' id='idSelect" + label + "'>" +
"<option>--Select Product" + label + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + ' <input type="button" value=" - " id="dltElement' + label + '" class="btn-minus pull-left" /></div>'
);
}); // Script for adding dropdown dynamically
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form-group">
<input type=button id=btnCompare value=btnCompare />
<div class="container" data-id="1">
<select id="idSelect1" name="idSelect1">
<option>--Select Product1--</option>
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
</select>
<input disabled type="button" class="btn-minus pull-left" id="dltElement1" value=" - ">
</div>
<div class="container" data-id="2">
<select id="idSelect2" name="idSelect2">
<option>--Select Product2--</option>
<option value="p1">Product 1</option>
<option value="p2">Product 2</option>
</select>
<input disabled type="button" class="btn-minus pull-left" id="dltElement2" value=" - ">
</div>
</div>
Edit 3:
Please find updated snippet. you need to have data-id="number" for all div.container, add class container and data-id to all the divs having select and button.
It is hard to have what you want since you can delete from the middle as well. You can have an array of deleted objects and update it everytime you delete or add into that. In this code I have added to disbaled input delete for 1 and 2 so that you can add and delete other 2. You can play around the logic.
It counts the number of divs in DOM and then checks if you are trying to add more than the limit, It then picks the last added in DOM and increments the data-id to use it as a label for the next select
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).
i.e.
$(document).on('event','selector',callback_function)
Example
As you have defined CSS class, use the to get the select element and perform removal operation.
$("#form-group").on('click', ".btn-minus", function(){
$(this).prev('select').remove();
});
$.fn.prev()
Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
you are assigning the <select> element an id that ends with a number, like this :
<select name='idSelect"+count+"' id='idSelect"+count+"'>
this means you end up with something like this :
<select name="idSelect1" id="idSelect1">
...
</select>
so the selector $("#idSelect") will never hit it unless it includes that number.
The part where you add the button :
'<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" />
has that same problem.
An easy way (though arguably not the best way) to achieve what you want is this :
function removeSelect(evt)
{
var selectBox = $(evt.currentTarget).parents(".group").find("select");
//do with select box as you will
}
$(document).ready(function() {
var count = 3;
$("#btnCompare").click(function() {
if (count > 4) {
alert("Only 4 options are allowed");
return false;
}
$("#form-group").append(
"<div class='group'>
"<select name='idSelect" + count + "' id='idSelect" + count + "'>" +
"<option>--Select Product" + counter + "--</option>" +
'<option value="p1">Product 1</option>' +
'<option value="p2">Product 2</option>' +
"</select>" + '<input type="button" value=" - " id="dltElement' + count + '" class="btn-minus pull-left" onclick="removeSelect(event)" /> </div>'
);
count++;
}); // Script for adding dropdown dynamically
});
What i want to achieve
I have got one static select html options, these options do not change but will determine what the other select boxes output.
<select id="firstselectbox">
<option value="first">This is the first</option>
<option value="second">This is the second</option>
<option value="third">This is the third</option>
<option value="fourth">This is the fourth</option>
<option value="fifth">This is the fifth</option>
</select>
Currently, the code i have written doesnt want to output the following:
Select 1: option selected first
Select 2: checks jSon file, finds first and all of the nodes (second layer) and list them. When a user selects that.
Select 3: displays the third layer
Please note the * is the option selected below - select 1 is static and select 2 and 3 are dynamic.
Select 1 Select 2 Select 3
first* London Famous Famous
second Jersey London Famous
third North*
fourth South East
fifth South West
sixth
What have i done so far
var datajson = {"first":[{"jesery":[{"id":"jesery","name":"Jesery","jesery":[{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"dontknow":[{"id":"dontknow","name":"Dont Know"}]}],"second":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}]}],"third":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"north":[{"id":"north","name":"North","north":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}]}],"forth":[{"north":[{"id":"north","name":"North","north":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"dontknow":[{"id":"dontknow","name":"Dont Know"}]}],"fifth":[{"london":[{"id":"london","name":"London","london":[{"id":"f2f","name":"London Famous"},{"id":"famous","name":"Famous Famous"},{"id":"distance","name":"Distance"}]}],"southeast":[{"id":"southeast","name":"South East","southeast":[{"id":"distance","name":"Distance"}]}]}]}
$("#firstselectbox").on('change', function() {
$("select#firstselectbox").html('');
var locations = datajson[$(this).val()];
var locationString = '';
$.each(locations, function(i, item) {
console.log(locations[i]);
locationString += '<option id="'+ locations[i].id + '" value="' + locations[i].id + '">' + locations[i].name + '</option>';
});
$('#secondselectbox').html(locationString);
});
Issue?
The following code is locationString += '<option id="'+ locations[i].id + '" value="' + locations[i].id + '">' + locations[i].name + '</option>'; is outputting unidentified.
However console.log(locations[i]); is outputting the array that that is selected from the static select box (first, second etc..). However, trying to separate that out seems to fail.
The current code is outputting unidentified.
Use unobtrusive JavaScript so you won't have to hunt bugs like this one:
$('#secondselectbox').empty()
$.each(locations, function(i, item) {
$("<option/>",{id:locations[i].id, value:locations[i].id, text:locations[i].name})
.appendTo('#secondselectbox')
})
Edit: Also there is a problem with your JSON structure. You basically have an array which contains a single object, so when you foreach the array you are at one level lower than where you need to be.
I have a <select> that I added with JQ ,
its loadded all options from a class (value + data) list return by $.ajax call, and load it to a div.
My code:
varTempDiv+= '<select class="selectFromList" width="200">';
$.each(data.d, function (index) {
varTempDiv+= '<option value="' + this.value >+ '">' + this.txtName + '</option>';
});
varTempDiv+= '</select>';
$("#loadedDiv").html(varTempDiv);
It work fine at all in chrome ,
but in ie8 its froze to some second append to list length.
The length start with 100 to 1000+ items.
How can i fix that things?
Thanks!!
Try using native for loop instead of jQuery.each. It should give you significant performance improvement especially if you have so many items in your array. Take a look at this comparison http://jsperf.com/jquery-each-vs-for-loop/69.
What happens if you change
varTempDiv+= '<option value="' + this.value >+ '">' + this.txtName + '</option>';
to
varTempDiv+= '<option value="' + this.value + '">' + this.txtName + '</option>';
Thousand items in a select also seems unusable, maybe you should consider a different design.
I have form fields which are displayed using Jquery on click of a button.
[select dropdown: conOperator] [textfield: conValue ] [select dropdown: conValuedd]
conValuedd is hidden by default.
I'm trying to figure out a way so that when I select either Apple or Banana in the first select drop down [conOperator], it hides the textfield conValue and displays drop down conValuedd instead. However, if I were to select Watermelon, it would display conValue and hide conValuedd again. Any ideas would be much appreciated.
$('<select id="conOperator' + num + '" name="conOperator' + num + '" class="standard_select" style="width:147px;">
<option>Watermelon</option>
<option>Apple</option>
<option>Banana</option>
</select>
<input type="text" id="conValue' + num + '" name="conValue' + num + '" class="short_input" value="" style="width:147px;">
<select style="display:none" id="conValuedd' + num +'" multiple="multiple" size="5">
<option value="option1">Blah</option>
<option value="option2">Blah</option>
</select>').appendTo('#addCondition');
Try something like a:
$('#addCondition').on('change','#conOperator' + num, function(e){
switch( $('option:checked',this).text() ){
case 'Apple':
case 'Banana':
$(this).nextAll(':text:first').hide();
$(this).nextAll('select:first').show();
break;
case 'Watermelon':
$(this).nextAll(':text:first').show();
$(this).nextAll('select:first').hide();
break;
}
});
$('#conOperator' + num).trigger('change');
DEMO
When you call appendTo(), the generated <select/> is added to the DOM so you can retrieve it with jQuery and add a listener on it.
$("#conOperator" + num).change(function() {
// Your logic here
}
I'm fairly new to both jQuery and JavaScript so can anyone please point out what I'm missing here?
I have a form with multiple pairs of select fields, where the content of the second field relies on the selection of the first one.
Once a value is chosen from the first one then a piece of jQuery code empties the corresponding second select options, gets new values as JSON and inserts them as new select values. All of this works with the code I've written.
However if a user has chosen a second value, I'd like to restore it if possible (meaning if the new values also include the one previously selected).
I tried to do this by first saving the second value and then trying to set it once the new options have been inserted. This did not work. However when trying to debug I inserted an alert() just before restoring the second value and with that in there it does work...
Am I missing something very basic here? Any help would be appreciated.
HTML:
<select name="party-0-first" id="id_party-0-first">
<option value="" selected="selected">---------</option>
<option value="1">first_value1</option>
<option value="2">first_value2</option>
<option value="3">first_value3</option>
<option value="4">first_value4</option>
</select>
<select name="party-0-second" id="id_party-0-second">
<option value="" selected="selected">---------</option>
<option value="1">second_value1</option>
<option value="2">second_value2</option>
<option value="3">second_value3</option>
<option value="4">second_value4</option>
</select>
<select name="party-1-first" id="id_party-1-first">
...
JavaScript:
$.fn.setSecond = function() {
var divName = $(this).attr("name");
divName = divName.replace('-first', '');
divName = divName.replace('party-', '');
// Save the currently selected value of the "second" select box
// This seems to work properly
setValue = $('#id_party-' + divName + '-second').val();
// Get the new values
$.getJSON("/json_opsys/", { client: $(this).val() },
function(data){
$('#id_party-' + divName + '-second').empty();
$('#id_party-' + divName + '-second').append('<option value="" selected="selected">---------</option>');
$.each(data, function(i, item){
$('#id_party-' + divName + '-second').append('<option value="' + item.pk + '">' + item.fields.name + '</option>');
});
});
// Here I try to restore the selected value
// This does not work normally, however if I place a javascript alert() before
// this for some reason it does work
$('#id_party-' + divName + '-second').val(setValue);
$(document).ready(function(){
$('[id*=first]').change(function() {
$(this).setSecond();
});
});
Well, it looks like your getJSON() call is involved in that issue.
Remember, from the start, all ajax request are ASYNC, means your last line of code
there is most likely executed before the getJSON() success eventhandler is called.
When you set the variable "setValue", try declaring it with var:
var setValue = $('#id_party-' + divName + '-second').val();
But I don't think that's the problem. The problem is that you're trying to reset the value in some code that's going to run before the getJSON is actually done. Try moving the thing that sets the value inside the function that's passed to getJSON.
$.getJSON("/json_opsys/", { client: $(this).val() },
function(data){
$('#id_party-' + divName + '-second').empty();
$('#id_party-' + divName + '-second').append('<option value="" selected="selected">---------</option>');
$.each(data, function(i, item){
$('#id_party-' + divName + '-second').append('<option value="' + item.pk + '">' + item.fields.name + '</option>');
});
$('#id_party-' + divName + '-second').val(setValue);
});