I'm trying to use javascript to make all elements in a given form with the readonly attribute editable on a click of a button.
so for i've only managed to get one input element to change as I was using the getElementById but as it is ID this is unique in HTML eyes.
How do I change this so I it targets all input elements with readonly?
see my code:
HTML:
Edit
<input class="form-control" type="text" id="editable" name="" value="someValue" readonly>
<input class="form-control" type="text" id="editable" name="" value="someValue2" readonly>
JAVASCRIPT:
document.getElementById('edit').onclick = function() {
document.getElementById('editable').readOnly = false;
};
Seeing as how you're open to a jQuery solution you could use:
$('#edit').click(function (e) {
e.preventDefault();
$('.form-control').removeAttr('readonly')
})
jsFiddle example
Note that since IDs must be unique I removed them and used the class to select the elements. The preventDefault is used to stop the link from being followed.
Try this
$("#edit").click(function() {
$("input.form-control").removeAttr("readonly");
});
If you use jQuery
Here is a plain javascript solution:
document.getElementById('edit').onclick = function(event) {
event.preventDefault();
var edits = [];
edits = document.getElementsByClassName('editable');
for(var i = 0; i<edits.length; i++){
edits[i].readOnly = false;
}
};
Notice
You had id='editable', I change it into class, cause you know ID is UNIQUE.
Here is a FIDDLE
Related
Here's what I'm essentially trying to do:
<input type="text" class="form-control" value="window.location.hash">
What's the proper way to insert the window.location.hash into the input's value?
Note: I've found several ways to do this when people are required to click a button, but nothing that explains how to do it automatically when the page loads.
You'll need to assign this after the page loads, or at least the element
<input type="text" class="form-control" id="hash" value="">
<script>
window.onload=function() {
document.querySelector("#hash").value = window.location.hash
}
</script>
Just get the element and change its value using JavaScript. In this Snippet, I'm redirecting to a different hash, just for example purposes.
const input = document.querySelector("input.form-control");
// Redirect to different hash for example
window.location.hash = "abcdef";
input.value = window.location.hash;
<input type="text" class="form-control" />
You need JS script for that:
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('location');
input.value = window.location.host; // change .host to .hash
})
<input id="location">
In my work we have to fill a lot of textboxes to do some validations. After all, we need to erase all - one by one - to restart the process.
Has some way to erase all textbox content with javascript (the only one method we can use now)? A for loop maybe?
You should put all the input fields in a form and then reset the form by the .reset() method.
document.getElementById("reset").onclick= ()=>{
document.getElementById("form").reset()
}
<form id="form">
<input/>
<input/>
</form>
<button id="reset">Reset</button>
See an example on W3Schools or the docs on MDN
If you want to restore the fields to their initial value, reset the form as suggested by #dota2pro's answer.
OTOH, if you want to clear the elements regardless of their initial value, you can query the elements using a type (aka "tag") CSS selector via Document.querySelectorAll()
and iterate through the elements as below:
function go() {
let inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
}
<input type="text" value="a"><br>
<input type="text" value="b"><br>
<input type="text" value="c"><br>
<br>
<button onclick="go()">click to clear</button>
Note that:
document.querySelectorAll('input') fetches all <input>s regardless of their type attribute.
document.querySelectorAll('input[type="text"]') fetches all <input type="text">.
document.querySelectorAll('textarea') fetches all <textarea>.
If you want to combine, you can use the comma combinator:
document.querySelectorAll('input[type="text"],textarea')
You can get in different ways in javascript:
By ID : document.getElementById("id")
By class: document.getElementsByClassName("class")
By tag:
document.querySelectorAll("input")
or Jquery
By ID : $("#id")
By class: $(".class")
By tag: $("input")
Read documentation about that here
tru
[...document.querySelectorAll('input')].map(x=>x.value='')
var clean = () => [...document.querySelectorAll('input')].map(x=>x.value='');
<button onclick="clean()">Clear</button><br>
<input type="text" value="some"><br>
<input type="text" value="short"><br>
<input type="text" value="text"><br>
Bellow code will select all editable text-boxes
document.querySelectorAll('input[type="text"]:not(:disabled):not([readonly]))')
If you have JQuery available, you can do:
$('input[type="text"]').val('');
Or, if you prefer native:
for(var i = 0; i < document.getElementsByTagName('input').length; i++){
document.getElementsByTagName('input')[i].value = '';
}
I am building a contact form, and I am having problems with jQuery. I want to select specific input fields that have an error and apply the class err. Unfortunately, my code selects all inputs when there is an error. I am having trouble identifying which part of my logic is wrong.
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var contact_label = $('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
$(contact_label).removeClass('err');
if (!$.trim($(label_check).val())){
$(contact_label).addClass('err');
}
});
});
The order of my HTML goes something like so:
#contact_body
<label>
<input>
</label>
This selects all input and textarea elements:
var contact_label = $('input[required=true], textarea[required=true]');
Instead, you should restrict it to the elements within the label:
var contact_label = $(this).find('input[required=true], textarea[required=true]');
Note that $(contact_label) and contact_label are equivalent in your code, as well as $(label_check) and label_check.
Also, you can use the state parameter of toggleClass() to simplify this:
contact_label.removeClass('err');
if (!$.trim(label_check.val())){
contact_label.addClass('err');
}
… to this:
contact_label.toggleClass('err', !$.trim(label_check.val()));
Here's the updated event:
$('#send_mail').click(function(){
$('#contact_body').find('label').each(function(){
var contact_label = $(this).find('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
contact_label.toggleClass('err', !$.trim(label_check.val()));
});
});
I think your original code would work if you just changed this line:
$(contact_label).addClass('err');
To this:
$(label_check).addClass('err');
Because $(contact_label) references all the required inputs, whereas $(label_check) references only the input being checked.
But your code could be simplified, and you make unnecessary calls to $(), giving it an argument that is already a JQuery object.
I also do not see that you need to loop through the labels. You could loop through the required inputs instead.
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
var $input = $(this);
$input.removeClass('err');
if (!$.trim($input.val())){
$input.addClass('err');
}
});
});
Which could be shortened by using the .toggleClass() function:
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
$(this).toggleClass('err', !$.trim($input.val()));
});
});
Notes:
The selector ':input' matches <input>, <select> and <textarea> elements.
This is a slightly different approach. Gives a bit more flexibility.
arr = ['first', 'last', 'email', 'msg']; //IDs of fields to check
$('#send_mail').click(function(){
$('input, textarea').removeClass('err');
for (var i=0; i<arr.length-1; i++) { //Loop through all field IDs
if ( $('#'+arr[i]).val() == '' ) {
$('#'+arr[i]).addClass('err').focus();
return false;
}
}
//AJAX to send email goes here
alert('Email sent');
});
.err{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="first">First Name:</label>
<input id="first" type="text" required /><br>
<label for="last">Last Name:</label>
<input id="last" type="text" required/><br>
<label for="email">Email:</label>
<input id="email" type="email" required /><br>
<label for="msg">Message:</label>
<textarea id="msg" required></textarea>
<button id="send_mail">Send</button>
you can simplify the code, there will be less mistakes:
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var field = $(this).find('[required=true]');
if ($.trim($(field).val())){
$(this).removeClass('err');
}
});
});
Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;
I want to know if its possible to change the name of the input tag with javascript or jquery, for example in this code :
<input type="radio" name="some_name" value="">
I want to change the some_name value when user select this radio button.
the reason what i want to do this is described here : How might I calculate the sum of radio button values using jQuery?
Simply elem.name = "some other name" or elem.setAttribute("name", "some other name") where elem is the element you want to alter.
And to do that on selection, use the onchange event:
<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">
And to apply that behavior to every radio button with that name:
var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
var elem = inputElems[i];
if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
elem.onchange = function() {
if (this.selected) {
this.name = "some other name";
}
};
}
}
But using jQuery for that is quite easier.
The jQuery way
$('input:radio[name="some_name"]').attr('name', 'new name');
Gumbo has the vanilla JavaScript way covered
Yes, you can change the name of any element with javascript. Keep in mind though that IE 6 and 7 have trouble with submitted forms where the input elements have been tinkered with in javascript (not sure if this exact case would be affected).
$('input:radio[name="some_name"]').attr('name', 'new_name');
Edit: To change it only when it is selected, here is the code for that:
$("input:radio[name='some_name']").click(function() {
if ($(this).attr('checked')) $("input:radio[name='some_name']").attr('name', 'new_name');
else $("input:radio[name='some_name']").attr('name', 'some_name');
});
Sure. If jQuery is your poison, this should do the trick:
$("input[name=some_name]").attr("name", "other_name");
I came up with this:
<input type="radio" name="some_name" value="" id="radios">
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#radios").click(function()
{
$(this).attr("name", "other_name");
});
});
</script>
Trying to change the name attribute of a radio button will cause strange, undesirable behavior in IE.
The best way to handle this is to replace the old radio button with a new one. This post may help you. If you are using jQuery, you can do it with the replaceWith function.
More information about changing name attributes in IE.