i would like to remove a hidden field from the form using jquery based on hidden field value.
please look the below html:
<input type="hidden" name="myvalue[]" value="value1"/>
<input type="hidden" name="myvalue[]" value="value2"/>
<input type="hidden" name="myvalue[]" value="value3"/>
i have jquery function which returns me the above value example:
$('#getValue').click(function(){
.... processing code here.....
return valueOfHiddenField;
});
now i would like to remove the hidden field from the form based on the value return by the getValue
so if the method returns me value1 then any input hidden field in the form with value as value1 should be removed. in this case the first input field of my html above.
any help or suggestion would be a great help ... thanks in advance
$('input[type="hidden"][value="+YOUR_VALUEVAR+"]').remove();
fiddle: http://jsfiddle.net/9tsgy/
You can iterate over input:hidden elements to check values and remove() based on value,
$("input:hidden").each(function () {
if (this.value == "value1") { // your condition here
$(this).remove()
}
}
$('#getValue').click(function () {
$(document).find("input[type=hidden]").each(function () {
if ($(this).value == 'Your Value') {
$(this).remove();
}
});
return valueOfHiddenField;
});
You can also do like this:
let hiddenValue = $(this).val();
$('input[type="hidden"][value="'+hiddenValue+'"]').remove();
Get the value of a hidden field and then use it dynamically and remove specific <input type="hidden">
Related
I am trying to change the attribute name="" value of an input field that is toggled once a check box is set and a toggled input is shown and filled out.
User checks a check box, once the check box is checked an input field shows where the title once was. I got this part covered.
Once the input field shows, I want to change the name attribute in that input field with the value the user inputs all before submission of form.
Here is the code I have tried...
document.getElementById('custom-check-box').addEventListener('click', function() {
if (this.checked) {
document.getElementById('custom-span').innerHTML = '<input type="text" id="customInputName" name="customInputName" placeholder="Name the custom attribute">';
} else {
document.getElementById('custom-span').innerHTML = 'Custom: ';
}
});
// this bit of code is not working as intended. I want to get the input
// value after the user changes or focus out of the input and then have that
// value input into the name attribute for the same input.
document.getElementById('customInputName').addEventListener('change', function() {
if (this.onChange) {
let value = document.getElementById('customInputName').value;
this.setAttribute("name", value);
}
});
<div title="'.$title.'" class="input-info">
<span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>
Error: Cannot read property 'addEventListener' of null
I think it is because the input is not set yet in the DOM. Should I set the input in HTML, hide it and then change the name attribute and then show it?
Any help would be greatly appreciated as I am a bit of a beginner with JavaScript.
Thank you in advance!
SEE ACCEPTED ANSWER FOR UPDATE ON WORKING CODE. -> Second snippit was added an edit to #CertainPerformance code that works better for my use.
I'd create the <input> outside of any of the handlers, and give it the listener which assigns its value to its name. When the checkbox is checked, append the input to the container, otherwise clear the container:
const input = document.createElement('input');
input.name = 'customInputName';
input.placeholder = 'Name the custom attribute';
const customSpan = document.getElementById('custom-span');
document.getElementById('custom-check-box').addEventListener('click', function() {
if (this.checked) {
customSpan.textContent = '';
customSpan.appendChild(input);
} else {
customSpan.textContent = 'Custom: ';
}
});
input.addEventListener('change', function() {
input.name = input.value;
});
<div title="'.$title.'" class="input-info">
<span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>
I am trying to get the values of each of the input field that are under same set. Below is my code:
Input field 1:
<input type="text" maxlength="255" name="amount[]" >
Input field 2:
<input type="text" maxlength="255" name="amount[]" >
and so on....the number of fields are variable.
Now I want to get the values the user typed in each of the field that is named . How to do that in jquery?
I have tried following code but it returns nothing:
$("input[name=amount[]]").val();
you can get all values in an array
var values = $('input[name="amount[]"]').map(function(){
return this.value;
}).get();
console.log(values);
Demo ---> http://jsfiddle.net/BFjp5/
Since there are multiple element with same name you need indexing:
$("input[name='amount[]']")[0].value;
Here is demo
and for getting all elements values:
$("input[name='amount[]']").each(function (i,v) {
alert(this.value);
});
Here is demo
by javascript
function getValues(){
var ids=document.getElementsByName('amount[]');
var ary=new Array();
for(var i=0;i<ids.length;i++){
ary[i]=ids[i].value;
}
return ary;
}
$("input[name='amount[]']")
This will get you a set of elements. You can get value of each of those elements by iterating over them.
$("input[name='amount[]']").each(function(){
$(this).val();
});
Try to pass the attribute value as a string since [ and ] are meta-characters,
var values = $("input[name='amount[]']")
.map(function(){ return $(this).val() })
.get().join('');
DEMO
You don't!
The whole point of ID's in the DOM is that they are unique.
I have a form with a lot of fields and want to clear all the default values (unchanged ones) for the input[type=text] when I click the button preferably using jQuery. I am using the button rather than submit because I am will be using the same button to then submit the form to a local script and then on to a third part for processing. But my script doesn't seem to be working.
A simplified version of the form:
<form name="cpdonate" id="cpdonate" method="post" action="" >
<input type="text" value="First Name" id="BillingFirstName" name="BillingFirstName" onFocus="clearField(this)" onBlur="setField(this)" />
<input type="text" value="Last Name" id="BillingLastName" name="BillingLastName" onFocus="clearField(this)" onBlur="setField(this)" />
<input type="hidden" name="Submit" value="Submit" />
<button id="cpbutton">Submit</button>
</form>
and the script I'm using:
<script type="text/javascript">
$(document).ready(function(){
// default values will live here
var defaults = {};
// Set the default value of each input
$('input[type=text]').each(function(){
defaults[$(this).attr('value')] = $(this).text();
});
// Functions to perform on click
$('#cpbutton').click(function(){
// clear unchanged values
$('input[type=text]').each(function(){
if (defaults[$(this).attr('value')] === $(this).text())
$(this).text('');
});
});
});
</script>
input doesn't have text, it has value and you can't rely on the attribute once user changes it, need to get it from the value property. Also, your defaults object won't locate the value if it is changed.
Am going to store each value on the elements itself using data()
Use val()
$(document).ready(function(){
// Set the default value of each input
$('input[type=text]').each(function(){
$(this).data('val', $(this).val());
});
// Functions to perform on click
$('#cpbutton').click(function(){
// clear unchanged values
$('input[type=text]').each(function(){
if ($(this).data('val') === $(this).val())
$(this).val('');
});
});
});
You should use defaults[$(this).attr('name')] instead of defaults[$(this).attr('value')] because when user changes value then attribute "values" value also changes
You may try this (Example)
// clear unchanged values
$('input[type=text]').each(function(){
if ($(this).val() == this.defaultValue) $(this).val('');
});
An input type=text has .val() jQuery method, not text() and use this.defaultValue to check the initial default value.
Can I somehow insert the required attribute into an input field only if a certain radio is checked?
I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.
My input looks like this:
<input type="text" name="ladder-meters" id="ladder-meters">
and should like this at the onchange event on the radio
<input type="text" name="ladder-meters" id="ladder-meters" required>
document.getElementById("ladder").addEventListener('change', function(){
document.getElementById("ladder-meters").required = this.checked ;
})
Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked with !this.checked
This may need some adjustment to suit your specific project.
This will work with this checkbox:
<input type='checkbox' id='ladder' name='ladder' />
Tried F. Orvalho, didn't work for me, I had to use
$('#ladder').change(function () {
if(this.checked) {
$('#ladder-meters').prop('required', true);
} else {
$('#ladder-meters').prop('required', false);
}
});
It could be usefull. Thx to F. Orvalho for the structure
Easy to achieve with jQuery:
$('#ladder').change(function () {
if($(this).is(':checked') {
$('#ladder-meters').attr('required');
} else {
$('#ladder-meters').removeAttr('required');
}
});
This question already has answers here:
Resetting a multi-stage form with jQuery
(31 answers)
Closed 9 years ago.
I am looking for a jQuery function that will clear all the fields of a form after having submitted the form.
I do not have any HTML code to show, I need something generic.
Can you help?
Thanks!
Note: this answer is relevant to resetting form fields, not clearing fields - see update.
You can use JavaScript's native reset() method to reset the entire form to its default state.
Example provided by Ryan:
$('#myForm')[0].reset();
Note: This may not reset certain fields, such as type="hidden".
UPDATE
As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger():
$('#myForm').trigger("reset");
UPDATE
If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.
To reset form (but not clear the form) just trigger reset event:
$('#form').trigger("reset");
To clear a form see other answers.
Something similar to $("#formId").reset() will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset() would "reset" form values to those previously submitted which will likely not be "".
One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():
function clearForms()
{
$(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(':checkbox, :radio').prop('checked', false);
}
If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):
function clearForm($form)
{
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.
Note that this will not clear placeholder text.
Set the val to ""
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />
You could also try something like this:
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
More info here and here
<form id="form" method="post" action="action.php">
<input type="text" class="removeLater" name="name" /> Username<br/>
<input type="text" class="removeLater" name="pass" /> Password<br/>
<input type="text" class="removeLater" name="pass2" /> Password again<br/>
</form>
<script>
$(function(){
$("form").submit(function(e){
//do anything you want
//& remove values
$(".removeLater").val('');
}
});
</script>
You can simply use the reset button type.
<input type="text" />
<input type="reset" />
jsfiddle
Edit: Remember that, the reset button, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" /> after press reset the field will reset the value inserted by user and come back with the word "name" in this example.
Reference: http://api.jquery.com/reset-selector/
I use following solution:
1) Setup Jquery Validation Plugin
2) Then:
$('your form's selector').resetForm();
function reset_form() {
$('#ID_OF_FORM').each (function(){
this.reset();
});
}
the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.
$.fn.resetForm = function() {
return this.each(function(){
this.reset();
});
}
Then just call it something like this
$('#divwithformin form').resetForm();
or
$('form').resetForm();
and of course you can still use it in the chain
$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')
Would something like work?
JQuery Clear Form on close
HTML
<form id="contactform"></form>
JavaScript
var $contactform = $('#contactform')
$($contactform).find("input[type=text] , textarea ").each(function(){
$(this).val('');
});
Simple and short function to clear all fields