I have created a template html block with allow me to copy that block when I click on Add button. This is done via append()
How to change the value of name='category[]' input field after it has been appended?
For example:
$('#add').click(function() {
$('#LinesContainer').append($('#templatePlan').html());
var getCategory = $("#selectCategory").val();
// How to put getCategory value into category[] field?
});
Select Category and click on + button
<div>
<select id="selectCategory">
<option value="New">New</option>
<option value="Old">Old</option>
</select>
<input value="+" id="add" type="button"/>
</div>
Template Block
<div id="templatePlan" style="display:none;">
<div style='padding: 5px; border: 1px solid white; background-color: #FFA86F;'>
<select name="selectType[]">
<option>Consumer</option>
<option>Business</option>
</select>
<input name='category[]' type='hidden' value='' />
</div>
</div>
<div id="LinesContainer"> </div>
I am not sure if this is a neat way to implement it, is there alternative better way?
Just select it. I'd recommend to use .clone() for the template instead of innerHTML, that will make the selection easier. Otherwise you might have multiple category inputs and have to use that last one.
$('#add').click(function() {
$('#templatePlan').children('div').clone().appendTo('#LinesContainer')
.find('input name="category[]"').val($("#selectCategory").val());
});
//after
var getCategory = $("#selectCategory").val();
//To set the actual input
$('input[type="hidden"]').val(getCategory);
//or to update the attribute rather
$('input[type="hidden"]').attr('name', 'category[' + getCategory + ']');
Related
Good Day Friends. I have a problem... Thanks, if you help me
I have a couple of inputs into a div. I copied that div with Clone function in java script (by click a button) and right now, I have two divs. but my problem:
1- I don't know, How can I get the values of inputs correctly (the input's names are the same)?
2- and I have a select input in div, that some inputs add or remove by choose each option of select input. Now after copied div, choose one option in div2, create changes in div1... and I don't want it !!
<div class="levels">
<div class="add_senario_level">
<span>Level 1</span>
<form>
<select name="condition" onchange="show_div(this,'shop during');">
<option selected="selected" disabled="disabled">choose condition</option>
<option>shop after registration</option>
<option>shop during</option>
</select>
<div id="shop_during" style="display:none;">
<input type="number" id="shop_during_num" name="shop_during_num" placeholder="Enter number">
<select id="shop_during_time" name="shop_during_time">
<option selected="selected">hour after registeration</option>
<option>day after registeration</option>
<option>week after registeration</option>
<option>month after registeration</option>
</select>
</div>
<div>
<button type="button" class="newLevel"> Add New Level </button>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function()
{
$(".newLevel").click(function()
{
$(".add_senario_level").clone().appendTo(".levels");
});
});
function show_div(obj, id)
{
txt = obj.options[obj.selectedIndex].text;
if (txt.match(id))
{
document.getElementById("shop_during").style.display = 'block';
}
else
{
document.getElementById("shop_during").style.display = 'none';
}
}
</script>
You can use jQuery's find function to find a child element and the attr function to get and set attribute values. You will want to do this to change on the id and name attributes for the input and select like below:
HTML
<input type="number" id="shop_during_num0" name="shop_during_num0" class="shop_input" placeholder="Enter number">
JavaScript
$(".newLevel").click(function()
{
const count = $('.add_senario_level').length;
const clone = $(`#add_senario_level${count - 1}`).clone();
const input = clone.find(`#shop_during_num${count - 1}`);
const select = clone.find(`#shop_during_time${count - 1}`);
input.attr('name', `shop_during_num${count}`);
input.attr('id', `shop_during_num${count}`);
select.attr('name', `shop_during_time${count}`);
select.attr('id', `shop_during_time${count}`);
clone.appendTo(".levels");
});
In the show_div method, you can use $(obj) to reference the select that called the function and show or hide the correct element with
$(obj).parent().find('#shop_during').css('display', 'block');
I'm trying to create a form that allows a user to enter their experience and education
I would like the user to be able to add and remove education or experience.
I am able to do this... sort of. Only the problem is my new divs that I am creating are being appended to the end of the page instead of being appended after the previous div.
These are my scripts:
$(document).ready(function() {
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name', 'input' + (++inputs));
$('.clonedInput:last').after(c);
});
$('.btnDel').click(function() {
if (confirm('continue delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled', ($('.clonedInput').length < 2));
}
});
});
$(document).ready(function() {
var inputs = 1;
$('#btnAdd2').click(function() {
$('.btnDel2:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name', 'input' + (++inputs));
$('.clonedInput:last').after(c);
});
$('.btnDel2').click(function() {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel2').attr('disabled', ($('.clonedInput').length < 2));
});
});
I understand it's bad form to duplicate code like this but I'm not sure how else to else to do it so that clicking the add button doesn't get pressed for the wrong div...
and my html is:
<form id="myForm">
<h2>Education</h2>
<p>Please add all of your education</p>
<div style="margin-bottom: 4px; border: 2px solid; border-style: dashed" class="clonedInput">
Level: <select>
<option value="secondary">Secondary</option>
<option value="someps">Some Post Secondary</option>
<option value="college">College</option>
</select> <br /> <br />
Did you receive a degree, diploma or certificate?<br />
<select>
<option value="certificate">Certificate</option>
<option>Diploma</option>
<option value="degree">Degree</option>
</select> <br />
<input type="button" class="btnDel" value="Remove Education" disabled="disabled" />
</div>
<div>
<input type="button" id="btnAdd2" value="add Education" />
</div>
<h2>Experience</h2>
<p>Please add all of your experience</p>
<div style="margin-bottom: 4px; class="clonedInput">
Position title: <input type="text"><br /> Years at position:
<input type="number"><br />
Responsibilities: <input type="text"><br />
<input type="text"><br />
Type: <select>
<option>Accounting, banking and Finance</option>
<option>Publishing & Journalism</option>
<option>Social Care & guidance work</option>
</select>
<input type="button" class="btnDel2" value="Remove Experience"
disabled="disabled" />
</div>
<div>
<input type="button" id="btnAdd2" value="add Experience" />
</div>
</form>
Any ideas on how I can fix my script so that when I click the add button for education, a new div containing all of the fields for "education" show up below the previous education box and the same for education?
Any help would be appreciated. Thanks!
Firstly, why do you have 2x $(document).ready? Combine your code into one.
The reason why your duplicated div appear at the end of the form is because both your Education and Experience divs have class="clonedInput", hence $('.clonedInput:last').after(c) causes the duplicated div to be placed after the Experience section (which happens to be the last div that matches the .clonedInput selector).
A solution would to be give each of these sets of divs their own unique class name, such as eduInput and expInput respectively.
The corrected code would hence be:
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.eduInput:first').clone(true);
c.children(':text').attr('name', 'input' + (++inputs));
$('.eduInput:last').after(c);
});
for the education div.
To clean up your code, I suggest binding both Add buttons to the same handler, but act upon them differently by checking the target parameter and determining which set (Education or Experience) to duplicate. Such as:
// single handler and click event for both buttons
var clickHandler = function (e) {
// determine which btnAdd was clicked, such as e.getAttribute('id')
}
$('.btnAdd').click(clickHandler);
But seriously you should clean up your code a little.
I need help about using append in jquery. Everytime I click button right btnRight the selected option value will add in the textarea so I used append to add the value in the textarea. It is already adding a value in the textarea but the value is "undefined,". can anyone help me why I am getting a value "undefined,"?
Sample HTML Code:
<textarea name="include_field_list" cols="70" rows="5" required="required" readonly="readonly" /></textarea>
<section class="container">
<div>
<select id="leftValues" size="5" multiple="multiple">
<option value="post_id">Post ID</option>
<option value="status">Status</option>
<option value="shipper_name">Shipper Name</option>
</select>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" size="4" multiple>
</select>
<div>
<input type="text" id="txtRight" />
</div>
</div>
SELECT, INPUT[type="text"] {
width: 160px;
box-sizing: border-box;
}
SECTION {
padding: 8px;
background-color: #f0f0f0;
overflow: auto;
}
SECTION > DIV {
float: left;
padding: 4px;
}
SECTION > DIV + DIV {
width: 40px;
text-align: center;
}
</style>
JQUERY Code:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$("#rightValues").append(selectedItem);
/***********This code has a problem************/
$value = $( "#leftValues>option:selected" ).val();
$("textarea[name=include_field_list]").append($value + ',');
/***************/
});
$("#leftValues").change(function () {
var selectedItem = $("#rightValues option:selected");
$("#txtRight").val(selectedItem.text());
});
});
there is silly mistake take place...
when user click on button the right hand side not remain selected values.
because it's move on right side... you just need to change your direction.
$value = $( "#rightValues>option:selected" ).text();
SEE DEMO
there is an other problem if user deselect any item on right side. then this value not append in textarea.. the better way to handle this use each option in right side..
SEE THIS DEMO
Second, $(textarea).append(txt) doesn't work like you think.
Instead of .append() sth to <textarea> element simply use:
var $textarea = $("textarea[name=include_field_list]"),
$oldValue = textarea.val();
$textarea($oldValue + 'new value text')
In this jsFiddle You have working solution
You can try this code..
$("textarea[name=include_field_list]").val($value + ',');
if you are appending value after existing, then get that value and pass that value in parameter too,
You have to correct ^^^^ indicated code in your code.
$value = $( "#leftValues option:selected" ).val();
^^^^
$("textarea[name=include_field_list]").val($value + ',');
^^^^^
If you call val() on a multiple-choice select list, you get an array instead of a string. So you are actually trying to append a "," to an array. Try this:
$value = $( "#leftValues>option:selected" ).val();
$("textarea[name=include_field_list]").append($value.join( ", " ) + ',');
The JSFiddle of the fix (Without CSS): http://jsfiddle.net/hyoLedxw/
I have this HTML code
<h3></h3><br></div>
<div style="border-left: solid #0a0a0a 1px; float:left; height: 80%; margin-top:7%; width: 10px;" ></div>
<div style="width: 49%; float: right;">
<h3></h3><br>
<input name="jurors" id="jurors" type="text" style="width: 80%;">
<br>
<input type="button" value="Add" class="addButton">
<br>
<br>
<br>
<br>
<select style="width:80%;height:250px; bottom: 0;" rows="10" multiple="multiple"></select>
And what I wana do with this is to get the value from the Input field by clicking the "add" button and add it to the select box. Also if posible to remove a value from the selct box by clicking on it. I need the select box values as a list to be inserted later into my DB.
I beleve this could be done with jQuery (adding and removing the values) but my knowledge of the language is too basic to do it.
Thank you for your help in advance.
I've come up with a Javascript/JQuery solution. Let's go through it so you know what's going on and if you need to change it you can. I've left your HTML pretty much the same (I've taken away some styling for the sake of development), anyway here it is:
<h3>Adding and removing options</h3>
<input name="jurors" id="jurors" type="text" style="width: 80%;">
<br>
<input type="button" value="Add" class="addButton" onclick="add();" /> <!-- The 'onclick="add();" will call a the Javascript function add() -->
<br />
<select id="mySelect" style="width:80%;height:150px; bottom: 0;" rows="10" multiple="multiple"></select>
Here's the Javascript/JQuery:
function add(){ // Our function called by your button
var x = $("#jurors").val(); // This is a JQuery function that'll get the value of a element with the ID 'jurors' - our textbox
$("#jurors").val(""); // Clear the textbox value
if(x==""){} // If there's nothing in the textbox
else{
$("#mySelect").append("<option value='"+x+"'>"+x+"</option>" ); // Get our select and add a option with the value of our textbox value with the text of the textbox input
}
}
$("#mySelect").change(function(e){ // This is called whenever the user selects a option
var x = e.target.value; // Get the value of the selected option
$("#mySelect option[value='"+x+"']").remove(); // Remove the selected option
});
Here's the link to the JSFiddle: http://jsfiddle.net/gS2jS/2/
When you use this code in your website, there are a few things you'll have to remember; import JQuery, put the code in the body and the code must be placed after the inputs etc required, here's the HTML with the required code:
<html>
<head>
</head>
<body>
<h3>Adding and removing options</h3>
<input name="jurors" id="jurors" type="text" style="width: 80%;">
<br>
<input type="button" value="Add" class="addButton" onclick="add();" /> <!-- The 'onclick="add();" will call a the Javascript function add() -->
<br />
<select id="mySelect" style="width:80%;height:150px; bottom: 0;" rows="10" multiple="multiple"></select>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!-- Import JQuery -->
<script>
function add(){ // Our function called by your button
var x = $("#jurors").val(); // This is a JQuery function that'll get the value of a element with the ID 'jurors' - our textbox
$("#jurors").val(""); // Clear the textbox value
if(x==""){} // If there's nothing in the textbox
else{
$("#mySelect").append("<option value='"+x+"'>"+x+"</option>" ); // Get our select and add a option with the value of our textbox value with the text of the textbox input
}
}
$("#mySelect").change(function(e){ // This is called whenever the user selects a option
var x = e.target.value; // Get the value of the selected option
$("#mySelect option[value='"+x+"']").remove(); // Remove the selected option
});
</script>
</body>
</html>
That answer was longer than I hoped, sorry about that. Anyways, if you need any help, don't hesitate to leave a comment.
Code below contains certain tags in all four.
Image-1
here is the code :
<div style='background-color:YellowGreen;height:20px;width:100%;margin-top:15px;font-weight: bold;'>
Delegate(s) details: </div>
<div style="border:1px solid black;"><br/>
<div id="delegates">
<div id="0">
Name of the Delegate:
<input name='contact_person[]' type='text' size="50" maxlength="50" />
Designation:
<select name='delegate_type_name[]' class='delegate_type'>
<option value='select'>Select</option>
<option value='Main'>Main</option>
</select>
</div><br/>
</div>
<div>
<input type="button" name="more" value="Add More Delegates" id="add_more" />
<br />
<br />
</div>
</div>
In the above code on line 5 where <div id="0"> changes to value 1 in script that I mentioned in "add_more"
And the javascript for "add_more" is given below
jQuery('#add_more').click(function(){
var id = jQuery('#delegates > div:last').attr('id');
var temp = "<div id='"+(parseInt(id)+parseInt('1'))+"'> Name of the Delegate: <input type='text' size='50' maxlength='50' name='contact_person[]' /> Designation:";
temp += "<select name='delegate_type_name[]' class='delegate_type additional_delegate'><option value='select'>Select</option><option value='Additional'>Additional</option><option value='Spouse'>Spouse</option></select> <input type='button' name='rem' value='Remove' id='remove' /></div><br/>";
jQuery('#delegates').append(temp);
});
In the javascript code above I have added a remove button in the temp+ variable
<input type='button' name='rem' value='Remove' id='remove' />
Image-2 shows the remove button every time I click on "Add more Delegates" button.
In the image-2 I click on Add More Delegates button it shows the "remove" button on the right of drop down select list.
I want a jQuery function for remove button, so that when I click on remove it should remove <div id="1"> and also reset content before removing the div tag. Below image-3 is the output that I want when I click on remove button.
code that I tried was this from some reference is this
jQuery('#remove').click(function(){
var id = jQuery('#delegates > div:last').attr('id').remove();
});
but no luck.
Thanks.
You can't give an element id that is only a number, it must be #mydiv1, #mydiv2 or something similar, i.e. beginning with a letter not a number.
For starters your markup is a total mess. There is no way you should be using for layout purposes. Read up on tableless layouts and css.
The first thing you need to change is the id's of your div. An id cannot start with a numeric. I suggest naming the first div delegate0. Secondly, you are adding a remove button on every new row with the same id - all id's on a page should be unique so i suggest you change this to class="remove".
As for your question, it really boils down to needing to add a jQuery handler to the remove buttons using the .livedocs method.
This is as simple as:
jQuery('.remove').live('click',function(){
$(this).closest('div').remove();
});
Also, you need to keep a running counter of the id of the items added, and increment this every time a new row is added.
var nextDelegate = 1;
jQuery('#add_more').click(function(){
... your code here
nextDelegate++;
});
Also, I removed the superfluous <br/> after each div.
Live example: http://jsfiddle.net/cb4xQ/