On click, clone element to variable and append it to another element - javascript

I have a form and I would like to set it up so that when a user enters/selects values into the inputs and clicks the "Add" button, it will clone each of the inputs/select boxes, assign them to a variable and then append them to another element below. What i have currently is just returning [object Object] instead of cloning the elements. Where am I going wrong?
$(function() {
$('button').click(function() {
var $name = $('#name').clone(),
$email = $('#email').clone(),
$package = $('#package').clone(),
$newRow = '<div class="name">' + $name + '</div><div class="email">' + $email + '</div><div class="package">' + $package + '</div>';
$('.row').append($newRow);
});
});
.row {
display:table-row;
}
.row > div {
display:table-cell;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="email" />
<select id="package">
<option value="one">Package One</option>
<option value="two">Package Two</option>
<option value="three">Package Three</option>
</select>
<button>ADD ROW</button>
<div class="row">
</div>

Append each cloned element to its own div. Then append all divs into the row.
Due to a bug, you must force value on the cloned select box
$(function() {
$('button').click(function() {
var $name = $('<div class="name"></div>').append($('#name').clone()),
$email = $('<div class="email"></div>').append($('#email').clone()),
$package = $('<div class="package"></div>').append($('#package').clone());
$package.find('#package').val($('#package').val());
$('.row').append($name, $email, $package);
});
});
.row {
display:table-row;
}
.row > div {
display:table-cell;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="email" />
<select id="package">
<option value="one">Package One</option>
<option value="two">Package Two</option>
<option value="three">Package Three</option>
</select>
<button>ADD ROW</button>
<div class="row">
</div>
One last thing. You shouldn't be recognizing elements by id= as those are meant to be unique per whole page. Try rewriting your code so you could use classes for selectors. For example:
<input class="i_name" />
...
$('.i_name').clone()

You just need to append the cloned objects.
$(function() {
$('button').click(function() {
var $name = $('#name').clone(),
$email = $('#email').clone(),
$package = $('#package').clone();
$('.row').append($name);
$('.row').append($email);
$('.row').append($package);
});
});
.row {
display:table-row;
}
.row > div {
display:table-cell;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="email" />
<select id="package">
<option value="one">Package One</option>
<option value="two">Package Two</option>
<option value="three">Package Three</option>
</select>
<button>ADD ROW</button>
<div class="row">
</div>

I don't fully understand what do you need but clone return an object that's why appending to a string will return into a [object Object]. Perhaps you could use outerHTML.
$(function() {
$('button').click(function() {
var $name = $('#name').clone();
$email = $('#email').clone();
$package = $('#package').clone();
$newRow = '<div class="name">' + $name[0].outerHTML + '</div><div class="email">' + $email[0].outerHTML + '</div><div class="package">' + $package[0].outerHTML + '</div>';
$('.row').append($newRow);
});
});
.row {
display:table-row;
}
.row > div {
display:table-cell;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="email" />
<select id="package">
<option value="one">Package One</option>
<option value="two">Package Two</option>
<option value="three">Package Three</option>
</select>
<button>ADD ROW</button>
<div class="row">
</div>

Related

append() in jquery not woring

I am new to jquery and ajax. I really need you help.
I have two select box, one dynamically add options to a select when the first select box is checked. I used ajax to dynamically get those values. I am getting values correctly from database. But when I try to append these options inside second select box it is not working. My code is below
$(document).ready(function() {
$("#categories").change(function() {
var categoryId = $("#categories").val();
//alert(categoryId);
if(categoryId == 2) {
$.ajax({
url: "<?= base_url();?>Web/getRateType",
method: "POST",
dataType: "json",
success:function(data) {
//alert(data[0].status);
$("#rate_container").css('display', 'block');
$("#expected_salary_container").css('display', 'none');
$("#rate_categories").empty();
// var str = '<label>Rate*</label></br>';
//str += '<select name="rate_categories" style="font-size:15px" id="rate_categories"><option value="0">Select</option>';
var str = '';
$.each(data, function(key, value) {
//alert(value['rate_id']);
str +='<option value="'+ value['rate_id'] +'">'+ value['rate_cat_name'] +'</option>';
});
alert(str);
//str += '</select>';
var x = $("#rate_categories").append(str);
if(x){
alert(x);
}
}
});//$("#rate_categories").append('<option value="'+ value.rate_id +'">'+ value.rate_cat_name +'</option>');
}
else if (categoryId == 1) {
document.getElementById("expected_salary_container").style.display = "block";
document.getElementById("rate_container").style.display = "none";
}
else{
document.getElementById("expected_salary_container").style.display = "none";
document.getElementById("rate_container").style.display = "none";
}
});
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<?php foreach($categories as $key => $value) { ?>
<option value="<?php echo $value['type_id']; ?>"><?php echo $value['cat_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
here alert(x) is working fine. but the html is not appending inside select box. could anybody please help
jQuery is referenced in the header:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first. However please check the network tab JS file load.
You should put the references to the jquery scripts first.
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.2.6.min.js"></script>
Please use compatible new jquery CDN Url in above script tag.
Examine the code below and see if that works for you. I've changed the vanilla JS to jQuery. You may need to re-insert your php code back in.
$(document).ready(function() {
//Hide everything
$("#expected_salary_container, #rate_container").hide();
$("#categories").change(function() {
var categoryId = $("#categories").val();
console.log(categoryId);
//alert(categoryId);
if (categoryId == 2) {
let data = ["Item 1", "Item 2", "Item 3"];
str = "";
$.each(data, function(key, value) {
//alert(value['rate_id']);
str += '<option value="' + value + '">' + value + '</option>';
console.log(str);
});
var x = $("#rate_categories").append(str);
$("#expected_salary_container").hide();
$("#rate_container").show();
} else if (categoryId == 1) {
$("#expected_salary_container").show();
$("#rate_container").hide();
} else {
$("#expected_salary_container").hide();
$("#rate_container").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<option value="2">Cat 1</option>
<option value="1">Cat 2</option>
<option value="2">Cat 3</option>
</select>
</div>
</div>
<div id="rate_container">
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>
<div id="expected_salary_container">
<div class="form-group">
<label>Salary*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>

generate dynamic div and retrieve value of input elements

I am having div with input elements with Add and Cancel buttons.
When user clicked on add Button,I need to generate div with the same input elements and capture the value to JSon object.
Here is my code snippet
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
I tried with clone and trying to retrieve values from the input elements inside div,but I am facing issue with getting values and generating ids.
$('#addBtn_' + count).click(function () {
var newel = $("#filterfields").clone(true);
var jsonData = [];
$(newel).insertAfter("#filterfields");
var index;
$("#filterfields").find('input:text,select').each(function () {
let str = '{"' + this.id + '":' + (this.value + '}';
jsonData.push(str);
}).end()
newel.find(':input').each(function () {
var oldId = $(this).attr("id");
var split = oldId.toString().split('_');
index = parseInt(split[1]);
var curId = split[0];
var newId = curId + "_" + index + 1;
this.id = newId;
}).end()
jsonData.push('"filterClause":' + $('input[name="inlineRadioOptions"]:checked').val() + '"');
});
Please suggest me if there is better way to achieve the similar function as I am not able to get values of input elements of current row.
Consider the following code.
$(function() {
function formToJson(fObj) {
var j = [];
fObj.children().not("button, label").each(function(i, el) {
// Will avoid buttons and labels
if (!($(el).is(":radio") && !$(el).is(":checked"))) {
// Will avoid unselected Radio Buttons
var d = {
nodeName: $(el).prop("nodeName"),
props: {
class: $(el).attr("class"),
id: $(el).attr("id")
},
value: $(el).val(),
name: $(el).attr("name")
};
if (d.nodeName != "SELECT") {
d.props.type = $(el).attr("type");
}
j.push(d);
}
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
As you are iterating over elements, it is best to use .each(). Using the proper selector, we can target just the form elements you want. You then want a condition to ensure that if a Radio Button is selected (or checked) that it is included and others are excluded.
The result is an Array of Objects that can be used to rebuild the HTML Structure or just build new copies.
Update
$(function() {
function formToJson(fObj) {
var j = [];
fObj.each(function(i, el) {
var d = {};
$("select, input", el).each(function(k, v) {
if (!($(v).is(":radio") && !$(v).is(":checked"))) {
d[$(v).attr("id")] = $(v).val();
}
});
j.push(d);
});
return j;
}
$("[id^='addBtn']").click(function() {
var jsonData = formToJson($("#filterFieldsForm"));
console.log(jsonData);
var filter = "Filter: ";
$.each(jsonData, function(key, item) {
if (key != 2) {
filter += item.value + " ";
} else {
filter += "'" + item.value + "' ";
}
});
$("<div>", {
class: "filter-results"
}).html(filter).appendTo("body");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filterfields" class="row collapse">
<form class="form-inline" id="filterFieldsForm">
<select class="form-control" name="TypeCode" id="filterType_0">
<option value="Type">Type</option>
<option value="SubmittedBy">SubmittedBy</option>
<option value="Date">Date</option>
<option value="Description">Description</option>
</select>
<select class="form-control" name="Filter" id="filterCondition_0">
<option value="Equal">Equal</option>
<option value="StartsWith">Starts With</option>
<option value="EndsWith">Ends With</option>
<option value="Greaterthan">Greater Than</option>
<option value="Lessthan">Less Than</option>
</select>
<input type="text" name="caseFilterText" class="form-control" id="filterText_0">
<input class="form-control" type="radio" name="inlineRadioOptions" id="andRadio_0" value="AND">
<label for="andRadio">AND</label>
<input class="form-control" type="radio" name="inlineRadioOptions" id="orRadio_0" value="OR">
<label for="orRadio">OR</label>
<button id="addBtn_0" type="button" class="btn btn-secondary">Add</button>
<button id="cancelBtn_0" type="button" class="btn btn-secondary">Cancel</button>
</form>
</div>
This will target the various rows and for each row, it will gather all the Select and Inputs.

Unhide A Div Tag On Radio Button Select

I am new to HTML/JQuery and am attempting to unhide a div tag based off of a radio button selection. In my instance below if the user selects SR readio button, I want to unhide the s div - likewise, if the user selects the C radio button, I want to unhide the C div
I put together the below syntax, but when the page loads regardless which radio button is pressed. Neither div becomes visible.
<script>
$(document).ready(function() {
$("input[name$='src']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#src" + test).show();
});
});
</script>
<Input type = 'Radio' Name ='src' value= 'sr'>SR<p>
<Input type = 'Radio' Name ='src' value= 'C'>C
<p><p>
<div id="st" class="desc">
SR:
<select name="sp" id="SR" visible="false">
<option selected="selected">All</option>
<?php
foreach ($qry2 as $SR) {
?>
<option value="<?= $SR->SR ?>"><?= $SR->SR ?></option>
<?php };
?>
</select>
</div>
<div id="c" class="desc" visible="false">
C:
<select name="C" id="C">
<option selected="selected">All</option>
<?php
foreach ($qry1 as $name) {
?>
<option value="<?= $name->C ?>"><?= $name->C ?></option>
<?php };
?>
</select>
</div>
Looks like you've almost got it.
IDs of the .desc elements don't match the selectors you build based on the clicked inputs' values. For example, if I click on the "SR" button, the code tries to show an element with ID "srcSR", which does not exist.
Here's an adjusted example:
$(document).ready(function() {
$("input[name$='src']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#list_" + test).show();
});
})
.desc {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Input type='Radio' Name='src' value='sr'>SR
<Input type='Radio' Name='src' value='C'>C
<div id="list_sr" class="desc">
SR:
<select name="sp" id="SR" visible="false">
<option selected="selected">All</option>
<option value="">STUFF</option>
</select>
</div>
<div id="list_C" class="desc" visible="false">
C:
<select name="C" id="C">
<option selected="selected">All</option>
<option value="">STUFF</option>
</select>
</div>

How to select dropdown by inserting value in the text box

Hello i have a dropdown which is fetching data from a database. Forget about the database, i have a text box in front of the dropdown select. The logic is if i type in the text the value should be selected automatically from the dropdown if the value typed in the text not matched with the values in the dropdown, then the user can select the dropdown. Any help would be much appreciated.
Here is my html code!
<div class="form-group">
<label class="col-sm-4 control-label">Scheme**</label>
<div class="col-sm-4">
<select class="form-control" name="scheme" id="scheme">
<?php
for ($column = 'A'; $column <= $lastcol; $column++) {
echo '<option value="' . $column . '">' . $worksheet->getCell($column . '1')->getValue() . '</option>';
}
?>
</select>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="txt_scheme" name="txt_scheme" placeholder="Or Type here">
</div>
</div>
In dropdown i m getting these values
QC code
Analyte
Assay Value
Assigned Value
STANDARDDEVIATION
ACCEPTABLEMIN
ACCEPTABLEMAX
Sample ID
Date
Try this code, then you can modified with your need.
$("#product").on("change keyup paste", function(){
var valuefound ='';
$("#platformid option").each(function(i){
if($(this).text().substring(0, 2).toLowerCase()==$("#product").val().substring(0, 2).toLowerCase() ){ valuefound = $(this).val(); } });
$('option:selected', 'select[name="platformid"]').removeAttr('selected'); $('#platformid option[value="' + valuefound + '"]').prop('selected', true); })
Working fiddle here https://jsfiddle.net/8xfqeb9y/
<label for="">Enter Value</label>
<input type="text" class="textVal">
<select name="" id="listItems">
</select>
var listItems = ["One","Two","Three","Four","Five","Six"];
for (var i = 0; i < listItems.length; i++) {
console.log(listItems[i]);
$("#listItems").append("<option>" + listItems[i] + "</option>")
}
$(".textVal").on("focusout",function(){
for (var i = 0; i < listItems.length; i++) {
console.log(listItems[i]);
if(listItems[i] == $(this).val()) {
$("#listItems").val($(this).val());
}
}
})
check now that values and texts are different and you can even select now by typing one
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#txtselect").keyup(function(){
$("#selbox > option").each(function() {
if($(this).text()==$("#txtselect").val())
{
$(this).attr('selected', 'selected');
}
});
});
});
</script>
</head>
<body>
<select id="selbox">
<option val="select">select</option>
<option val="123">one</option>
<option val="abc">two</option>
<option val="23sfd">three</option>
<option val="27345">four</option>
</select>
<input type="text" id="txtselect"/>
</body>
</html>
check this you will get solution run snippet and type "one"
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#txtselect").keyup(function(){
$("#selbox").val($("#txtselect").val());
});
});
</script>
</head>
<body>
<select id="selbox">
<option val="select">select</option>
<option val="one">one</option>
<option val="two">two</option>
<option val="three">three</option>
<option val="four">four</option>
</select>
<input type="text" id="txtselect"/>
</body>
</html>
Try this
<script type="text/javascript">
function getselected(elem)
{
var textvalue = $(elem).val();
if(textvalue != '')
{
$('select').removeAttr('disabled');
$('select option').removeAttr('selected');
$('select option').each(function(){
if ($(this).html().indexOf(textvalue) > -1)
{
$('select').val($(this).attr('value'));
}
});
}
else
{
$('select').val('');
$('select').attr('disabled','disabled');
}
}
</script>
<input type="text" name="name" value="" onkeydown="getselected(this)">
<select disabled="disabled">
<option value="">Select</option>
<option value="1">QC code</option>
<option value="2">Analyte</option>
<option value="3">Assay Value</option>
<option value="4">Assigned Value</option>
<option value="5">STANDARDDEVIATION</option>
<option value="6">ACCEPTABLEMIN</option>
<option value="7">ACCEPTABLEMAX</option>
<option value="8">Sample ID</option>
<option value="9">Date</option>
</select>

append() working only first time..when appending same code on same div

$('.addvalue').change(function(){
val_id = this.id;
counter_btn++;
counter_inp++;
if( $('#'+val_id).val() == '1'){
$('#div'+ val_id).append('<input id="myInput'+counter_btn +'" class="form-control" required placeholder="Enter Text"
style="margin-top: 5px;border-color: green;border-width: medium;" type="text" />');
$('#div' +val_id).append(' <button type="button" id="mybtn'+counter_btn +'" class="btn btn-success button_class btn-xs" style="margin-top: 5px;" onclick="addtest('+counter_btn+')" >ADD</button>');
$("#myInput"+counter_btn).focus();
}else{
$('#div'+ val_id).remove();
}
});
<html>
<select class="form-control newclass addvalue"
name="CandInv-54" id="sugar_id">
<option value="">Select Value</option>
<option value="absent">ABSENT</option>
<option value="PRESENT(+++)">PRESENT(+++)</option>
<option value="1">ADD</option>
</select>
<div id="divsugar_id">
append code will go here...
</div>
</html>
The problem with this line :
$('#div'+ val_id).remove();
this code is removing the content from dom. Try to remove html of the div instead. replace the code with this
$('#div'+ val_id).html('');

Categories

Resources