jquery remove removes all the thing which is appending after? - javascript

Below is my code. I am removing some elements in html with class and it removes but I am inserting some elements with class .als-h-f before a input field. but remove function removes these also. please suggest why this is happening?
if (jQuery(this).find('input[type=hidden]').length > 0) {
jQuery('.als-h-f').remove();
jQuery(this).find('input[type=hidden]').each(function () {
jQuery('#search').before(jQuery(this));
});
}
<div class="als-cont">
<input type="hidden" class="als-h-f" name="als_id" value="11">
<input type="hidden" class="als-h-f" name="als_fname" value="Rajesh">
<input type="hidden" class="als-h-f" name="als_lname" value="Sharma">
<input type="text" name="search" id="search">
</div>

You can't find an HTML element that you've removed from the DOM. Store them in a variable before you remove them and then add them again.
$input = $('#search');
$hiddens = $('.als-h-f');
$hiddens.remove();
$hiddens.each(function(index, $hidden){
console.log($hidden);
$input.before($hidden);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="als-cont">
<input type="hidden" class="als-h-f" name="als_id" value="11">
<input type="hidden" class="als-h-f" name="als_fname" value="Rajesh">
<input type="hidden" class="als-h-f" name="als_lname" value="Sharma">
<input type="text" name="search" id="search">
</div>

Related

jquery add remove form input on toggle

I have the following html and form elements
<div class='ticket-sold' id='1' >RAFFLE-1-NOVEMBER</div>
<div class='ticket' id='2'>RAFFLE-2-NOVEMBER</div>
<div class='ticket' id='3'>RAFFLE-3-NOVEMBER</div>
<div class='ticket' id='4'>RAFFLE-4-NOVEMBER</div>
<div class='ticket' id='5'>RAFFLE-5-NOVEMBER</div>
<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="UK" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="payer_email" value="customer#example.com" />
<input name="item_name_1" value="TICKET NUMBER 5" id="input_5" type="hidden">
<input name="item_name_2" value="TICKET NUMBER 20" id="input_20" type="hidden">
<input name="item_name_3" value="TICKET NUMBER 27" id="input_27" type="hidden">
<input type="hidden" name="amount_1" value="10" id="input_5" />
<input type="hidden" name="amount_2" value="10" id="input_20" />
<input type="hidden" name="amount_3" value="10" id="input_27" />
<input type="submit" name="submit" value="Submit Payment"/>
</form>
Basically, I have jquery that when the Div class 'ticket' is selected, the 'amount' field is updated based on the number of 'ticket' elements selected.
var counter = 0;
$(".ticket").on("click", function() {
$(this).toggleClass("green");
$(this).toggleClass('selected');
var selectedIds = $('.selected').map(function() {
return this.id;
}).get();
var id = $(this).attr('id');
if(!$(this).hasClass('selected')) {
$('#paypal_form #input_' + id).remove();
counter--;
} else {
counter++;
$('#paypal_form').append('<input type="hidden" name="item_name_'+counter+'" value="TICKET NUMBER ' + id + '" id="input_'+id+'">');
$('#paypal_form').append('<input type="hidden" name="amount_'+counter+'" value="' + $(".ticketprice").text() +'" id="input_'+id +'">');
}
$(".totaltickets").text(selectedIds.length -1);
$(".totalprice").text((selectedIds.length - 1)*$(".ticketprice").text());
What I would like to do, is at the same time of the onclick function on the 'ticket' div, I would like another input type ie <input type="hidden" name="item_name" value="Selected ID from Div"> added dynamically to the Form ("paypal_form"). And if the 'ticket' DIV is toggled, ie Clicked to deselect the item, the added element should be removed.
thanks
Craig.
You could approach it similar to this. It checks if the class selected is assigned to the selected div. If so, it appends a hidden input with a specific ID to the form. If the div is unselected, it removes that input from the form.
$(document).ready(function() {
$(".ticket").on("click", function() {
$(this).toggleClass("green");
$(this).toggleClass('selected');
var selectedIds = $('.selected').map(function() {
return this.id;
}).get();
var id = $(this).attr('id');
if(!$(this).hasClass('selected')) {
$('#paypal_form #input_' + id).remove();
} else {
$('#paypal_form').append('<input type="hidden" id="input_' + id + '">');
}
$('[name=amount]').val((selectedIds.length - 1) * $(".ticketprice").text());
$('[name=item_name]').val((selectedIds.length - 1) + " Ticket(s) selected");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='ticket-sold' id='1'>RAFFLE-1-NOVEMBER</div>
<div class='ticket' id='2'>RAFFLE-2-NOVEMBER</div>
<div class='ticket' id='3'>RAFFLE-3-NOVEMBER</div>
<div class='ticket' id='4'>RAFFLE-4-NOVEMBER</div>
<div class='ticket' id='5'>RAFFLE-5-NOVEMBER</div>
<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="UK" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="payer_email" value="customer#example.com" />
<input type="hidden" name="item_name" value="" />
<input type="hidden" name="amount" value="0" />
<input type="submit" name="submit" value="Submit Payment" />
</form>
figured it out with the following
var ii = 1;
$("input[name^='item_name']").each(function(i){
$(this).attr('name', 'item_name_' + ii++);
});
var ii = 1;
$("input[name^='amount']").each(function(i){
$(this).attr('name','amount_' + ii++);
});
thanks for your help :)

getElementById and multiple forms

I am having this situation with many forms (for instance I show you a coupe of them):
<form method="POST" enctype="multipart/form-data">
<textarea name="content" id="content" class="form-control" required=""></textarea>
<input name="code" id="code" type="hidden" value="1180224194">
<input name="postId" id="postId" type="hidden" value="167">
<button class="btn btn-commenta">Say something</button>
</form>
<form method="POST" enctype="multipart/form-data">
<textarea name="content" id="content" class="form-control" required=""></textarea>
<input name="code" id="code" type="hidden" value="95959622661">
<input name="postId" id="postId" type="hidden" value="144">
<button class="btn btn-commenta">Say something</button>
</form>
And I have some javascript like this:
<script type="text/javascript">
$("form").submit(function (e) {
e.preventDefault();
var comment = document.getElementById("content").value;
var postId = document.getElementById("postId").value;
var code = document.getElementById("code").value;
if(comment && postId && code){
$.ajax({
type: 'POST',
...SOME AJAX
});
}
else {
console.log("error");
console.log(comment);
console.log(postId);
console.log(code);
}
return false;
});
</script>
Everything works fine when I have a single form (or when I use the first one), but when I try to get the values of the inputs in a different form than the first one, I get an error and my fields are empty.
How can I tell the script to select the values (with getElementById) of the submitted form? I tried with "this" but the console tells me "Cannot read property 'getElementById' of undefined".
The id attribute should be unique in the same document, use common classes instead like :
<form method="POST" enctype="multipart/form-data">
<textarea name="content" class="form-control content" required=""></textarea>
<input name="code" class="code" type="hidden" value="1180224194">
<input name="postId" class="postId" type="hidden" value="167">
<button class="btn btn-commenta">Say something</button>
</form>
Then get the element values using this to refer to the curren form :
var comment = $(".content", this).val();
var postId = $(".postId", this).val();
var code = $(".code", this).val();
Hope this helps.
$("form").submit(function(e) {
e.preventDefault();
var comment = $(".content", this).val();
var postId = $(".postId", this).val();
var code = $(".code", this).val();
console.log(comment);
console.log(postId);
console.log(code);
if (comment && postId && code) {
console.log("ajax query");
} else {
console.log("error");
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" enctype="multipart/form-data">
<textarea name="content" class="form-control content" required=""></textarea>
<input name="code" class="code" type="hidden" value="1180224194">
<input name="postId" class="postId" type="hidden" value="167">
<br>
<button class="btn btn-commenta">Say something</button>
</form>
<form method="POST" enctype="multipart/form-data">
<textarea name="content" class="form-control content" required=""></textarea>
<input name="code" class="code" type="hidden" value="95959622661">
<input name="postId" class="postId" type="hidden" value="144">
<br>
<button class="btn btn-commenta">Say something</button>
</form>
Try using different id's for different elements. Id's should always be unique. If you want to use the same name for multiple elements (e.g for styling) use a class.
I suggest changing your ID's to something like:
<form method="POST" enctype="multipart/form-data">
<textarea name="content" id="content1" class="form-control" required="">
</textarea>
<input name="code" id="code1" type="hidden" value="1180224194">
<input name="postId" id="postId1" type="hidden" value="167">
`enter code here`<button class="btn btn-commenta">Say something</button>
</form>
<form method="POST" enctype="multipart/form-data">
<textarea name="content" id="content2" class="form-control" required="">
</textarea>
<input name="code" id="code2" type="hidden" value="95959622661">
<input name="postId" id="postId2" type="hidden" value="144">
<button class="btn btn-commenta">Say something</button>
</form>
https://www.w3schools.com/tags/att_global_id.asp W3Schools explains:
"The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet,
and by JavaScript (via the HTML DOM) to manipulate the element with
the specific id."

Usage of radio value in ID selector

Given this html:
<form action="">
<div id="choices">
<input type="radio" name="stype" id="opt1" value="input1_div" checked=""/> Opt1
<input type="radio" name="stype" id="opt2" value="input2_div"/> Opt2
</div>
<div id="stypes">
<div id="input1_div">
<input type="text" id="input1" name="input1" placeholder="input1"/>
</div>
<div id="input2_div" style="display: none;">
<input type="text" id="input2" name="input2" placeholder="input2" disabled=""/>
</div>
</div>
<div id="#sbutton">
<input type="submit" id="input3" value="Submit"/>
</div>
</form>
I use following jQuery to hide/disable input fields based on selected radio buttons:
jQuery('#choices input').each(function() {
var item = this;
$(this).click(function() {
if($('input[type=radio][name=stype]').is(':checked')) {
$('#stypes > div').hide();
$('#stypes input').not("#sbutton").prop('disabled', true);
$('#' + $(item).val()).fadeIn();
$('#' + $(item).val() + ' input').prop('disabled', false);
}
});
});
All-in-One in this jsfiddle.
I'm particularly unsure about my technique to incorporate radio value into the id selector:
$('#' + $(item).val()).fadeIn();
$('#' + $(item).val() + ' input').prop('disabled', false);
What is the correct way to do it? Other tips regarding my jQuery?
First of all, you don't need a sophisticated jQuery.each loop to bind the click and to define this. In each event handler this will be the caller of the function. In your case it is enough to have click function for all of them.
As you said in comments, it's only matter of presentation. I prefer to have one field instead of two fields. Even I prefer to have a fixed name for this text input, though in order to make it very similar to your example I change the name and placeholder accordingly.
$(function(){
$('#choices input').click(function() {
var newName = $(this).val(),
newPlaceholder = $(this).attr("data-placeholder");
$('#interchangable_input[name!='+newName+']').hide()
.attr("name", newName)
.attr("placeholder", newPlaceholder)
.fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="choices">
<input type="radio" name="stype" id="opt1" data-placeholder="Input one" value="input1" checked=""/> <label for="opt1">Opt1</label>
<input type="radio" name="stype" id="opt2" data-placeholder="Input two" value="input2"/> <label for="opt2">Opt2</label>
</div>
<div id="stypes">
<input type="text" id="interchangable_input" name="input1" placeholder="Input one"/>
</div>
<div id="#sbutton">
<input type="submit" id="input3" value="Submit"/>
</div>
</form>
Few more suggestions:
You can use <label for="target id"> for each option label in radio buttons or checkboxes. It will work fine with click event handler, even if the user clicks on the label instead of the button itself.
You can hid some information as data-* attribute in html5. You don't need to necessarily use value.
Update for multiple items
In case of group of multiple items in form, I can imagine a form with different sections or pages. The <fieldset> can be use to group these items. In HTML5 you could just disable the fieldset tag by <fieldset disabled> when you change the form page with jquery. (With exception of IE browsers). Because of this exception we need to disable all items in subforms. In order to handle this part, I defined a class .form-element which applies for all form inputs. You can also use <div> instead of <fieldset>, then you will need to track their enable/disable status.
$(function(){
// initialization by disabling form-elements and hiding them
$("#subforms fieldset[disabled]").hide();
$("#subforms fieldset[disabled] .form-element").attr('disabled','disabled');
// choice tracker
$('#choices input').click(function() {
var $target = $($(this).attr("data-subform")),
$oldElement = $("#subforms fieldset:not([disabled])");
$oldElement.attr('disabled','disabled').hide();
$oldElement.find(".form-element").attr('disabled','disabled');
$target.removeAttr("disabled");
$target.find(".form-element").removeAttr("disabled");
$target.fadeIn();
});
});
fieldset {
border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="choices">
<input type="radio" name="stype" id="opt1" data-subform="#subform1" value="subform1" checked=""/> <label for="opt1">Opt1</label>
<input type="radio" name="stype" id="opt2" data-subform="#subform2" value="subform2"/> <label for="opt2">Opt2</label>
</div>
<div id="subforms">
<fieldset id="subform1" >
<input class="form-element" type="text" name="input1_1" placeholder="Input one"/>
<input class="form-element" type="text" name="input1_2" placeholder="Input two"/>
</fieldset>
<fieldset id="subform2" disabled>
<input class="form-element" type="text" name="input2_1" placeholder="Input one"/><br />
<textarea class="form-element" name="input2_2" placeholder="Input two"></textarea><br />
<input class="form-element" type="checkbox" name="input2_3" id="input2_3" /> <label for="input2_3">check this first</label>
</fieldset>
</div>
<div id="#sbutton">
<input type="submit" id="input3" value="Submit"/>
</div>
</form>

How to change style using javascript?

<div class="club_member">
<input type="text" size="5" onclick="this.value=''" name="scienceClub" value="2">
</div>
How can I use a simple javascript command to change the value to "0" and place a 'disable=""' in the input style?
Use object.value to set the value and object.disabled to disable the input in Javascript.
Demo:
document.getElementById("button").addEventListener("click", function(){ // I have added a sample button for testing
var inputElementObject = document.getElementById("input"); // get the input element object
inputElementObject.value = "0"; // set the value
inputElementObject.disabled = true; // set the disabled property
});
<div class="club_member">
<!-- set an ID for the input element -->
<input type="text" size="5" onclick="this.value=''" name="scienceClub" value="2" id="input">
<button id="button">Click me!</button>
</div>
Check out how to set the properties for <input> here on MDN.
First set id in your control like this
<input type="text" id="myControl" size="5" onclick="this.value=''" name="scienceClub" value="2">
Then Try like this in script
var control=document.getElementById("myControl");
control.value=0;
control.setAttribute("disabled", true);
The below snippet demonstrates how to change the value and disable the input using strictly JavaScript.
document.getElementById("input").value = "0";
document.getElementById("input").disabled = true;
<div class="club_member">
<input type="text" size="5" onclick="this.value=''" name="scienceClub" value="2" id="input">
</div>
Using the same code as you posted. you just have to change its value and it gets disabled.
<div class="club_member">
<input type="text" id='something' size="5" onclick="this.value='0'; this.setAttribute('disabled','true');" name="scienceClub" value="2">
</div>
<div class="club_member">
<input type="text" id='something' size="5" onclick='this.value="0"' name="scienceClub" value="2">
<button onclick="document.getElementById('something').setAttribute('disabled','true');"> Lock the value </button>
</div>

Safari- HTML form is getting submitted twice. How to prevent it?

I have the following code
function submitSelf() {
var adhocMainJspPane = getFrameObject('adHocMainJSPPane',openerObject);
document.Form.action="something";
document.getElementById("tabID").value = adhocMainJspPane.cubeTreeFrame.document.getElementById("arePropertiesChanged").value;
document.selfCloseForm.target="advancedPropertiesJSPPane";
var tmpSum = getTmpSum();
document.selfCloseForm.action += "&tmpChk="+tmpSum;
document.selfCloseForm.method="post";
document.selfCloseForm.submit();
}
There is no other submit in the script.
The Html is
<BODY onload="submitSelf();">
<FORM name="selfCloseForm" id="selfCloseForm" action="" method="post">
<INPUT type="hidden" id="tabID" name="tabID" value="">
<INPUT type="hidden" id="fromPage" name="fromPage" value="">
<INPUT type="hidden" id="elementNo" name="elementNo" value="">
<INPUT type="hidden" id="elementName" name="elementName" value="">
<INPUT type="hidden" id="cubeAction" name="cubeAction" value="">
<INPUT type="hidden" id="arePropertiesChanged" name="arePropertiesChanged" value="">
</FORM>
<BODY>
The above for is submitted twice on SAFARI browser. How can I prevent it from doing so.

Categories