I have a piece of JS that appends the following to a web form on the click of a button. When the div .remove is clicked the closest new-attribute div is removed. It works fine.
<div class="new-attribute">
<h3>New Attribute</h3>
<label for="attributeName3">Name:</label>
<input class"attribute"="" type="text" name="attributeName3">
<label for="attributeType3">Type:</label>
<select id="t" class="attribute" name="attributeType3">
<option value="text" selected="">Text</option>
<option value="checkbox">Checkbox</option>
<option value="select-list">Select Option List</option>
<option value="notes">Notes</option>
</select>
<div class="option"></div>
<div class="remove">Delete</div>
</div>
In the div "option" I have code to add another form field on the selection of "select-list" in the select input. It does not work. I do not know why. No variable names are clashing. I'm away I shouldnt give the select an id because it is recurrent, I just want to get it working before I make it compliant.
Heres the Js that I'm having trouble with:
//select temp
var select="<div class=\"new-option\">"
+ "<h3>new option</h3>"
+ "<label for=\"attributeName"+count+"\">New otion:</label>"
+ "<input class\"attribute\" type=\"text\" name=\"attributeName"+count+"\">"
+ "</div>";
//get value of select
$('#t').change(function() {
var selectVal = $('#t :selected').val();
if (selectVal == "select-list") {
$(this).closest('.option').append(select);
}
});
The code works with $(select).appendTo('.option');
However it appends the code to every instance of the "option" class on the page. I only want it to append to the current or closest one.
Thank you in advance
The problem is because closest() looks up the DOM for the nearest parent element matching the selector, but .option is a sibling of #t. Try using next() instead:
$('#t').change(function() {
if ($(this).val() == "select-list") {
$(this).next('.option').append(select);
}
});
Try this
http://jsfiddle.net/7WC4G/1/
$('#bob').change(function(){
$('#nuform').append('<p>your new form here</p>');
});
Avoid using next, prev as it could fail if you change the order.
Instead try using siblings instead of closest in your code:
$(this).siblings('.option').append(select);
Read more about it here: http://api.jquery.com/siblings/
Related
$(document).ready(function() {
var element;
$(".form-element").on("mousedown", function(event){
element = $('<form><select name="dropdown"><option>Select...</option><option value="new-dropdown">add new...</option><option value="machine3">Machine 3</option><option value="machine4">Machine 4</option></select></form>');
$("#body-div").append(element);
});
});
The items in the list currently are just there for testing. But I need to be able to click on an add new option and add a new list item.
Working Fiddle
It looks like you were trying to dynamically add the entire form, but you only need to add additional option elements to your select section of your form.
To do this add this HTML
HTML
<input id="text-to-add" type="text" value="Machine 3">
<button id="new-item">Add to dropdown</button>
<form>
<select name="dropdown">
<option>Select...</option>
<option>Machine 1</option>
<option>Machine 2</option>
</select>
</form>
Then to dynamically add a select element use the append jQuery function.
jQuery
$(document).ready(function () {
$('#new-item').click(function() {
console.log($('#text-to-add').val());
$('select').append( '<option>' + $('#text-to-add').val() + '</option>' );
});
});
First add a new id for both the select tag and the option tag with the value "new option";
element = $('<form>
<select name="dropdown"
id="sel"><option>Select...</option>
<option value=
"new-dropdown"id="anew">add new...
</option></select></form>');
now im assuming that you already have the values for both the value and the text for that option let both of them be x and y respectively;
now add an onClick handler to #anew to append #sel with a new option with value x and text y:
z=$('<option value="'+x+'">'+y+'</option>');
$("#anew").onClick(function(){
$("#sel").append(z);
});
hope it solves your problem
I'm trying to edit the selected value of a select2. So I did this simple code:
http://jsfiddle.net/rcky9/2/
HTML
<select id="sel" style="width: 100%">
<option value="1">Hello</option>
<option value="2">Friends</option>
<option value="3">Stackoverflow</option>
</select>
<br><br>
<button id="addok">Add OK</button>
JS
$(document).ready(function () {
$("#sel").select2();
$("#addok").click(function() {
actual_value = $("#sel").find(':selected').text();
if (actual_value.indexOf(" OK") > -1){
return
}
newtext = actual_value + " OK";
// this works.
$("#sel").find(':selected').text(newtext);
// this does not works.
$('#s2id_sel').find('.select2-choosen').text(newtext);
});
});
As you see, after pressing the button, looks like nothing had changed, but if you open the dropdown, the OK was added successfully at the current item.
The problem appears when I try to modify the actual value located in a div with select2-choosen css class. I can't access it by this way.
Do you have any idea, advice or tip to do this?
Firing the change() on select will show the appended ok, you need to trigger change() There is no element with id s2id_sel and class .select2-choosen to last statement wont change the text.
Live Demo
$("#sel").find(':selected').text(newtext).change();
I have array of select dom and input textbox . On blur event of input(of perticular index) want to set the element in select dom value of same index.
My bind is working but after each blur event for different input box it is retiurning 0.
I am not able to set the select value i.e. (drop down)as per given index
JSFiddle
My code is following.
$(document).ready(function (){
var i =1;
$('#addme').on('click', function(){
var test = '<tr class="employee"><td><input type="text" id="emp_id['+i+']" /></td><td><select id="emp_name['+i+']" '
test += '<option value="-1" >Please Select </option><option value="e0001" >James Smith</option><option value="e0002" >Roger Sm</option>'
test +='<option value="e0003" >Elina Lobo</option></select></td></tr>'
$('#addme').after(test);
i++;
});
$(".employee input").live('blur',function(){
var inputIndex = $(this).index();
var inputValue = $(this).val();
alert("Input Index is :" + inputIndex + ' and value is ' + inputValue);
$('#emp_name[inputIndex]').each(function(){
if(this.value == inputValue){
$('#emp_name[inputIndex]').val($(this).val());
return false;
}
alert("Please iput valid value");
$('#emp_name[inputIndex]').val('-1');
});
});
});
</script>
<table />
<tr class="employee">
<td><input class="employee" type="text" id="emp_id[0]" /></td>
<td><select id="emp_name[0]" name="emp_name">
<option value="-1" >Please Select </option>
<option value="e0001" >James Smith</option>
<option value="e0002" >Roger Sm</option>
<option value="e0003" >Elina Lobo</option>
</select></td>
</tr>
<input type="button" id="addme" value="ADD ME"/>
</body>
</html>
You would need to delegate the events as you are adding the elements dynamically on the click of the button..
So $(".employee input").live('blur',function(){
should look something like this
$(staticContainer).on('blur',".employee input", function(){
staticContainer is the element that is already in the DOM when the elements are bound with the element.
Closer the container better the performance.
Also you have multiple issues with your code..
It is a better idea to append the rows to the table, so that the selector returns the right element inside the table.
$('#addme').after(test);
Supposed to be
$('table').append(test);
Next this selector does not replace the index value
$('#emp_name[inputIndex]')
supposed to be
$('#emp_name[' + inputIndex + ']')
Lastly the way you are accessing the indexes is completely wrong.
You are trying to get the current input with respective to the other elements . So
var inputIndex = $(this).index();
supposed to look like
var inputIndex = $('input').index(this); // which will give the right value.
Check Fiddle
First,jQuery .Index() means find the index of e's all siblings,not the index of the selector field,if you want to do so,you need a selector parameter.
So
var inputIndex = $(this).index();
should change to
var inputIndex = $(this).index(".employee input");
then your index part will work fine.
Second,I actually don't understand your blur event code part.You said you want to set the same index of select dom,why you compare the value?And you use the jQuery attribute selector and I didn't see any match element.I guess you try to select all select doms,and you try to alert on loop?I don't think it's a good idea.
I think you should rebuild this part,it has no logic and very hard to read now.
I want to retrieve the id of my option that I selected. Over here you can see my HTML.
<select name="zaal" id="zaal">
<DIV CONTENTEDITABLE="FALSE" ID="MACONTAINER" MACONSTRAINT="" MAPARAMETER="ZALEN">
<DIV CONTENTEDITABLE="TRUE" ID="MAITEM">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</DIV>
</DIV>
</select>
I am doing it like this.
var selectVal = $("#zaal :selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
But for some reason it won't work.
Can anybody help?
EDIT
Ok the divs are the problem. But I need those to get my values from my database.So I think I need to find another solution than a select.
$("#zaal option:selected").attr('value'); // will return you ~#ITEM.ID~
To get the id
$("#zaal option:selected").attr('id'); // will return you ZAALNAME
To get id on selection change try this:
$('#zaal').on('change', function() {
// To get id
$('option:selected', this).attr('id');
$('option:selected', this).attr('value'); // return the value of selected option
// To get the select box value
var value = this.value;
});
Maybe try:
$("#zaal option:selected").val();
Also, try moving the divs outside of the select element.
Look at this question:
<div> and <select> tags
You can only put <option> or <optgroup> inside a <select>. If you want to put anything else in there you have to make some kind of list yourself.
Why would you like to put any div inside a select anyway?
If I put the HTML you gave me (with edited strings) inside Google Chome, this is what is made of your code:
<select name="zaal" id="zaal">
<option value="x" id="ZAALNAME">X, Y</option>
</select>
$("#zaal option[value='0']").text()
Try this:
var selectVal = $("#zaal option:selected").val();
var id = selectVal.substring(1);
console.log("id is: " + selectVal);
The html should be
<select name="zaal" id="zaal">
<option value="~#ITEM.ID~" id="ZAALNAME">~ITEM.ID~, ~ITEM.NAME~</option>
</select>
$('#zaal').change(function(){
alert($($(this)+':selected').attr('id'));
});
Fiddle http://jsfiddle.net/cBaZ7/1/
val() will retrieve the value of the selected option. It is not the id
So try this:
$("#zaal option:selected").attr("id")
I don't care about the content in the form, just want to add a new set of them every time I click add. I will however be adding some conditional fields. But with that in mind, do I actually need to iterate ids? And is the clone event the best way to handle this?
<div id="wrapper">
<div id="condition-1">
<select id="trigger-1" class="trigger">
<option value="0">Select...</option>
<option value="1">View Count</option>
<option value="2">Comment Count</option>
</select>
<select id="operator-1" class="operator">
<option value="0">Select...</option>
<option value="1">Is Greater Then</option>
<option value="2">Less Than</option>
</select>
<div id="input-1" class="input">
<input id="number-1"></input>
</div>
</div>
<div id="add-1" class="add">Add more</div>
I've been digging through a lot of examples of jQuery .clone() ,have not been able to apply any examples to a structure like this. My goal is to add a new set of form elements every time I click "Add more". I don't care if it clones the actual content, just want to clone and then iterate the id's appropriately.
I tried using something similar to:
var cur_num = 1;
var cloned = $("#condition-" + cur_num).clone(true, true).get(0);
++cur_num;
cloned.id = "condition-" + cur_num; // Change the div itself.
$(cloned).find("*").each(function(index, element) { // And all inner elements.
if(element.id)
{
var matches = element.id.match(/(.+)_\d+/);
if(matches && matches.length >= 2) // Captures start at [1].
element.id = matches[1] + "-" + cur_num;
}
});
$(cloned).appendTo($("#condition-wrapper"));*/
The above block of code will clone and append the block I want. But as it iterates the first condition id to #condition-2, every block after is coming up #condition-2 and I have no idea how to change the children of condition-1 to trigger-2 operator-2. Any help is appreciated, thank you!
try this
$(function(){
$('.add').bind('click',function(){
var $this=$(this),
$cloned=$this.prev().clone(),
re=/(\d+)$/,
counter=1,
cid=$cloned.attr('id').replace(re,function(n){
return counter+=parseInt(n);
});
$cloned.attr({id:cid})
.find('[id]')
.each(function(i,o){
var iid=$(o).attr('id').replace(re,counter);
$(o).attr({id:iid});
})
.end()
.insertBefore($this);
});
})