javascript remove "disabled" attribute from html input - javascript

How can I remove the "disabled" attribute from an HTML input using javascript?
<input id="edit" disabled>
at onClick I want my input tag to not consist of "disabled" attribute.

Set the element's disabled property to false:
document.getElementById('my-input-id').disabled = false;
If you're using jQuery, the equivalent would be:
$('#my-input-id').prop('disabled', false);
For several input fields, you may access them by class instead:
var inputs = document.getElementsByClassName('my-input-class');
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
Where document could be replaced with a form, for instance, to find only the elements inside that form. You could also use getElementsByTagName('input') to get all input elements. In your for iteration, you'd then have to check that inputs[i].type == 'text'.

Why not just remove that attribute?
vanilla JS: elem.removeAttribute('disabled')
jQuery: elem.removeAttr('disabled')

Best answer is just removeAttribute
element.removeAttribute("disabled");

To set the disabled to false using the name property of the input:
document.myForm.myInputName.disabled = false;

$("#input-id").attr("disabled", false)

method 1 <input type="text" onclick="this.disabled=false;" disabled>
<hr>
method 2 <input type="text" onclick="this.removeAttribute('disabled');" disabled>
<hr>
method 3 <input type="text" onclick="this.removeAttribute('readonly');" readonly>
code of the previous answers don't seem to work in inline mode, but there is a workaround: method 3.
see demo https://jsfiddle.net/eliz82/xqzccdfg/

Related

How to get data attribute from radio button with JavaScript?

I want to get the data-price value from radio button which is checked. I tried something like that:
<input type="radio" name="vehicletype" id="vehicletype" value="{{$vehicletypeData->id}}" data-price="{{$vehicletypeData->km_rate}}" required="">
var vehicleTyp=document.getElementById("vehicletype");
var vetselindx=vehicleTyp.options[vehicleTyp.selectedIndex];
var prikm=vetselindx.getAttribute("data-price");
But this does not work. How can I solve this issue?
document.getElementById("vehicletype");
This gets the element with that id. The single element with that id. Multiple elements in a document cannot share an id.
vehicleTyp.options
Select elements have options. Radio buttons do not.
To find the checked element you should:
Get all the radio buttons. Consider getElementsByName
Loop over them until you find one where the checked property is true
Once you have found the element you are looking for you can use getAttribute("data-price"); or the dataset property.
You can reference the custom data- attributes of an element like so:
const el = document.getElementById("vehicletype");
const price = el.dataset.price;
For more information see the MDN docs on using data attributes.
Note: If you have a second dash in the attribute name e.g. data-price-new the dataset object property will reflect this in camelcase. dataset.priceNew
Working code, using getElementsByName
<input class="form-check-input" type="radio" data-type="one-time" name="payment-radio-btn" value="200" id="flexRadioDefault1" checked />One Time
<input class="form-check-input" type="radio" data-type="two-time" name="payment-radio-btn" value="300" id="flexRadioDefault1"/>Two time
<p> <button onClick="performAction()">Submit</button> </p>
function performAction(){
var amount = 0;
var type = '';
var radios = document.getElementsByName('payment-radio-btn');
for (var radio of radios) {
if (radio.checked) {
amount = radio.value;
type = radio.getAttribute("data-type");
}
}
alert(type)
}
Codepen-link

Getting data from input using JavaScript

I am trying to get a value out of a <input type='num'> with JavaScript I am using the following code:
Choose a number between 1 and 5 <input type='num' name="input">
<button id="btn">Click me!</button>
<script>
var input;
document.getElementById('btn').onclick = function(){
input = document.getElementById('num');
alert(input); //To check what value input has
</script>
This should get a value but I just get a null what am I doing wrong?
You have not defined your id. Also I guess your input type should be number.
<input type='number' name="input" id="num">
^^^^^^^^^^^^ ^^^^^^^^
And to alert its value you need to use
alert(input.value) //.value is used to get value of input
There are more than one problems with your code
1) You have to close the bracket of your function
it should be
document.getElementById('btn').onclick = function(){
input = document.getElementById('num');
alert(input); //To check what value is outputted
}
2)
input = document.getElementById('num');
The getElementById() method returns the element that has the ID
attribute with the specified value.
so ID attribute is essential here and in your code there is no ID attribute defined so you have to defined it first
like
<input type='number' id="num" name="input">
3) document.getElementById('num'); does not return the value of input field
it returns object
so if you want value then use the following code
document.getElementById('num').value;
4) your input type="number"
for the desired output you can use following code
Choose a number between 1 and 5 <input type='number' name="input" id="myid">
<button id="btn">Click me!</button>
JS
var myButton = document.getElementById("btn");
myButton.onclick = function()
{
alert(document.getElementById("myid").value); //where does id come from?
}
The above method is pure JS if you need jquery method you can refer below
$( "#btn" ).click(function() {
var input=$("#myid").val();
alert(input)
});
getElementById() works on elements with id attribute. So, as you have not put id attribute in your input type, it is not able to find the element with id=num.
Just add id="num" in your input element and then you are good to go.

Accessing Input element through input name in javascript

I want to access the following code using java script. Can anyone help me please? I'm a beginner to JavaScript.
<input type="text" name="username" />
I wish to access the element from its name property. An alert box needs to be shown if the length of element value is less than 6.
Use getElementsByName() method,
document.getElementsByName('username')
getElementsByName() returns an array of elements.
The getElementsByName() method returns a collection of all elements in the document with the specified name
var x = document.getElementsByName("username")[0].tagName;
Its better you can use id instead of name if it is unique.
<input type="text" id="username" />
var x=document.getElementById("username");
Try using document.getElementById(), need to specify unique id
var usrtxt = document.getElementById('usrtxt');
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" id='usrtxt' value='admin' />
Try using document.getElementsByTagName()
var inputArray = document.getElementsByTagName('input');//gives array
var usrtxt = inputArray[0];//get first element
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" value='admin' />
Probably the input is in a form like:
<form ...>
<input name="username">
...
</form>
and probably you want to validate it when the form is submitted, so in that case you likely have a listener on the form like:
<form onsubmit="return validate(this)" ...>
and in the validate function:
function validate(form) {
// get input as form.username
if (form.username.value.length < 6) {
alert('Username must be 6 or more characters long');
// Prevent form submission
return false;
}
}
You may want to be more sophisticated with the UI (your users will appreciate it), but the above shows the basics.
If you wish to identify particular element using Name then use getElementsByName function
Javascript:
var x = document.getElementsByName('username');
If you consider to use the Jquery then please use following code.
Jquery:
$('[name="username"]');
Learn more about Jquery Selectors
Update:
var x = document.getElementsByName('username'); // X is an array here as getElementsByName returns collection i.e. Array
var val = x[0];//get first element
if(val.value.length < 6) // Check if its value greater than 6
{
alert('boom !!');
}
}

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

Categories

Resources