add more add less using jquery clone with incrementing id - javascript

Curerntly working on jquery clone where I need to addrow and delete rows I have searched lot in stackoverflow and in google based on that i understand a bit on how jquery clone will work.
Any suggestion please
Here is the jquery code.
var count=0;
$(document).on("click", ".phn_btn_more", function () {
var $clone = $('.cloned-row:eq(0)').clone();
//alert("Clone number" + clone);
$clone.find('[id]').each(function(){this.id+='someotherpart'});
$clone.attr('id', "added"+(++count));
$('.cloned-row:eq(0)').after($clone);
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row').length;
if(len>1){
$(this).closest(".btn_less1").parent().parent().parent().remove();
}
});
With the current code updated code I can able to increment id dynamically but it cloning two times.
with this code when i try to click add more button it was cloning the div but i am getting two div instead of one and Iam trying to add id and name incrementing dynamically
I know it may be a possible duplicate but still I am not getting why I am not able to incrementing id and name. For btn less for the first div btn_less class won't be available once user click add more from second add less button should appear
Here is the html code
<div class="em_pho cloned-row" id="phone_content">
<select id="sel_phntype" name="sel_phntype" class="sslt_Field">
<option selected='selected' value="">Phone Type</option>
<option value="BUSN">Business</option>
<option value="CAMP">Campus</option>
<option value="CELL" >Cellphone</option>
<option value="CEL2">Cellphone2</option>
<option value="FAX">FAX</option>
<option value="HOME">Home</option>
<option value="OTR">Other</option>
</select>
<span class = "ph-inline">
<input type="text" class="cc_field" placeholder="Country Code" id="txt_CC" maxlength="3" name="txt_CC" />
<input type="text" class="pn_field" placeholder="Phone Number" id="txt_Pno" name="txt_Pno" />
<input type="radio" name="preferred" id="rad_Prf" value="preferred">
<label class="radio-label">Preferred</label>
<!--<button class="btn_more" id="buttonvalue"></button>-->
<input type="button" class="phn_btn_more" id="buttonvalue"/>
</span>
</div>
Kindly help me
Thanks & regards
mahadevan

Not sure if this is what you wanted.
JSfiddle
Let me know if I missed out anything or if anything is wrong.
JQuery
var count=0;
$(document).on("click", ".phn_btn_more", function () {
var $clone = $('.cloned-row:eq(0)').clone();
//alert("Clone number" + clone);
$clone.find('[id]').each(function(){this.id+='someotherpart'});
$clone.find('.phn_btn_more').after("<input type='button' class='btn_less1' id='buttonless' value = 'remove'/>")
$clone.attr('id', "added"+(++count));
$(this).parents('.em_pho').after($clone);
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row').length;
if(len>1){
$(this).parents('.em_pho').remove();
}
});

Related

make diffrence between objects that created with clone() in java script

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

Using innerHTML of <select> for windows.open()

On a page of my website I want user to select one choice of a and when they click on "connect" it open a new tab with the correct link.
code :
<select name="choice" id="choice">
<option value="Server1.html">Server1</option>
<option value="Server2.html">Server2</option>
<option value="Server3.html">Server3</option>
</select>
<input type="button" name="go_button" id= "go_button" value="go" onclick="go_to_the_link()"/>
<script>
function go_to_this_link(){
var element = document.getElementById("choice");
var link = element.innerHTML;
myWindow = window.open(link,"_blank");
}
</script>
According to the documentation this should works ... but since I'm new to JS and not expert in HTML I must have failed something.
I want to use JS only and make something that also works with datalist.
Any help is welcome !
Solved:
Ok I had 2 problem :
In order to post this on stackoverflow I changed all my variable and function name, and I forgot to change one ...
As said in the comment, I needed to use "value" and not innerHTML. I tried with value once but it also failed that's why I gave up this, I guess something else was wrong.
Thx for helping solving the problem !
(working) code :
<select name="choice" id="choice">
<option value="Server1.html">Server1</option>
<option value="Server2.html">Server2</option>
<option value="Server3.html">Server3</option>
</select>
<input type="button" name="go_button" id= "go_button" value="go" onclick="go_to_the_link()"/>
<script>
function go_to_the_link(){
var element = document.getElementById("choice");
var link = element.value;
myWindow = window.open(link,"_blank");
}
</script>

Javascript onchange function not working on select tag

I made 2 input fields and 1 select field and I applied onchange() function to select tag which calls javascript and that script make calculation and show it in other two fields
but it is not working for some syntax or logic reasons. please take a look at my code ,any help would be appreciated.
<html>
<head>
<script type="text/javascript">
function update() {
var x = document.getElementsByName("n_person").value;
document.getElementsByName("m_income").value= x*5;
document.getElementsByName("y_income").value= x*4;
}
</script>
</head>
<body>
<div class="elist"> <span class="b_text"><span>*</span>Level 1:</span>
// here is select tag where I put onchage function <select class="ifield" name="n_person" onChange="update()">
<option value="" selected="selected">Choose no. of person referred</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
// These are teh input where resultant value will appear <input type="text" value="" placeholder="Your weekly Income..." name="m_income" id="weekly_income" class="field" readonly required />
<input type="text" value="" placeholder="Your day Income..." name="y_income" id="day_income" class="field" readonly required/>
</div>
<!--elist-->
</body>
</html>
See this fiddle
Updated JS
function update() {
var x = document.getElementsByName("n_person")[0].value;
document.getElementsByName("m_income")[0].value = x * 5;
document.getElementsByName("y_income")[0].value = x * 4;
}
The problem with your JS was you was not targetting the correct HTML elements using getElementsByName.
Please read more about it here
The method getElementsByName returns, as its name indicates, a list of elements with the specified name and not just one. In your case, the names are unique to the document and the method will return a list with just one value, but you'll still need to index this list. Therefore, you must change this:
var x = document.getElementsByName("n_person").value;
to
var x = document.getElementsByName("n_person")[0].value;
Do this also for the other uses of getElementsByName and your code will work.

how do i make my onchange function generic?

My Javascript function checks for radio button selection and displays the appropriate drop down box. but this code is not generic, i tried using "this" but it doesn't help.. can this actually be generic?
CODE:
function change(s)
{
if(document.getElementById("viewstate").checked==true)
{
document.getElementById("state").style.display="inline";
document.getElementById("cat").style.display="none";
}
else
{
document.getElementById("state").style.display="none";
if(document.getElementById("viewcat").checked==true)
{
document.getElementById("cat").style.display="inline";
}
else
document.getElementById("cat").style.display="none";
}
}
Front end radio button
<input type="radio" name="viewrecord" value="viewstate" onchange="change('state')" required="" id="viewstate"> View by State
<select name="stat" id="state" style="display:none;">
<option selected disabled>Select State</option>
<input type="radio" name="viewrecord" value="viewcat" required="" onchange="change('cat')" id="viewcat">View By Agency
<select id="cat" name="che" style="display:none" required="">
You can try with this snippet
JS
document.addEventListener('click',function(event){
var tar = event.target.id;
if(tar ==="viewstate"){
document.getElementById("state").style.display="inline";
document.getElementById("cat").style.display="none";
}
else if(tar==="viewcat"){
document.getElementById("state").style.display="none";
document.getElementById("cat").style.display="inline";
}
},false)
WORKING COPY
What else I tried?
My primary idea was to add a class to next select tag. For example if you select radio#viewstate it will add a class to closest select element. Then just loop through all the select tag and whoever dont have this class , hide them.
But since you are using display:none nextSibling will not work.For why nextSibling wont work you can take a look at difference between it visibility:hidden
Also note in the demo that I have used label tag with input
If by generic you mean to make the function to be able to work for any similar selection process without depending on the hard-coded values of the selection inputs, this is one way I thought of doing it :
function change(selectorId, selectorClass) {
// Get all the selector elements you use.
var rS = document.getElementsByClassName( selectorClass );
// Out of the elements you fetched above, make the one with
// id = selectorId visible, rest hidden.
for(var i = 0; i < rS.length; ++i)
rS[i].style.display = (rS[i].id == selectorId) ? "inline" : "none";
}
In the HTML part add a class to every select input you want to use with the radio values:
<input type="radio" name="viewrecord" value="viewstate" onchange="change('state', 'record-selector')" required="" id="viewstate"> View by State
<select class='record-selector' name="stat" id="state" style="display:none;">
<option selected disabled>Select State</option>
<input type="radio" name="viewrecord" value="viewcat" required="" onchange="change('cat', 'record-selector')" id="viewcat">View By Agency
<select class='record-selector' id="cat" name="che" style="display:none" required="">
With this you can use the same function for similar selection process on different forms.

jQuery loop over html, on change, find class, remove it

So I've got multiple forms with selects on a page. For each form I want the submit button to have a class of disabled until an option is selected, at which point the button should lose the disabled class (each form must work independently of the others). I can't seem to get this working using Next or Find. Here's my code:
<-- FORM ONE -->
<form>
<label for="available-countries-#variables.x#">Available Countries</label>
<select id="available-countries-#variables.x#" class="form-control available-countries-selector">
<option value="0">-- Select Country --</option>
<option value="1">Australia</option>
<option value="2">Brazil</option>
</select>
<button type="submit" class="btn btn-default disabled" role="button">Submit</a>
</form>
<-- FORM TWO -->
<form>
<label for="available-countries-#variables.x#">Available Countries</label>
<select id="available-countries-#variables.x#" class="form-control available-countries-selector">
<option value="0">-- Select Country --</option>
<option value="1">Argentina</option>
<option value="2">France</option>
</select>
<button type="submit" class="btn btn-default disabled" role="button">Submit</a>
</form>
-- JS --
$('.available-countries-selector').change(function(){
if($(this).val() !== '0'){
$(this).find('btn-default').removeClass('disabled');
} else {
$(this).find('btn-default').addClass('disabled');
}
});
Any help would be appreciated
You need to look for the button in the current form. Best way to do that is using closest().
var isEnabled = $(this).val() !== '0';
$(this).closest("form").find('btn-default').toggleClass('disabled', !isEnabled);
How I would code it with event bubbling:
$(document).on("change", ".available-countries-selector", function(){
var isDisabled = $(this).val() === "0";
$(this).closest("form").find('btn-default').toggleClass('disabled', isDisabled);
});
ideally you would set document to an element that is closer to the forms.
In the JS context, the this is the <select> element. Since the btn-default is not inside the select, it will not find it with that code.
Instead you can go to the closest form parent and find it from there:
$(this).closest("form").find('btn-default').removeClass('disabled');
The submit button is not within the selector you are using so $(this).find will not work. However, you can use $(this).next() since the submit button is immediately after the select dropdown, like this:
$('.available-countries-selector').change(function(){
if($(this).val() !== '0'){
$(this).next().removeClass('disabled');
} else {
$(this).next().addClass('disabled');
}
});
JSFiddle
You're closing your <button>s with a </a> and your find() is not looking for a classname (because you've excluded the dot) nor can you find a sibling. Use next([selector]) to find the next .btn-default:
$('.available-countries-selector').change(function(){
if($(this).val() !== '0'){
$(this).next('.btn-default').removeClass('disabled');
} else {
$(this).next('.btn-default').addClass('disabled');
}
});
http://jsfiddle.net/mL9h2fof/
UPDATE (thanks #TrueBlueAussie)
You could use .toggleClass to make this even simpler:
$('.available-countries-selector').change(function(){
$(this).next('.btn-default').toggleClass('disabled', $(this).val());
});
http://jsfiddle.net/mL9h2fof/1/

Categories

Resources