I want to get the id of input using it's name,and to empty the input field.But it's not working.Is it possible?
html:
<input type="text" id="1" name="Color" maxlength="2" />
jQuery:
var myId="#";
myId=myId + $('[name="Color"]').attr('id');
$($myId).var('');
You can do this:
let id = $('input[name$="Color"]').val('').attr('id');
console.log(id);
$(`#${id}`).val('');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="1" name="Color" maxlength="2" />
You can set the input value using the val() function.
<input type="text" id="1" name="Color" maxlength="2"/>
var myId='#' + $('[name="Color"]').attr('id');
$(myId).val('');
To get the input value use it like this:
$(myId).val();
Try this code.
const myId = $('input[name="Color"]').attr('id');
$("#"+myId).val(''); // you can set any value here or you can perform any other operations on this element -> $("#"+myId)
On first line of this JS code, we are getting id attribute and then on second line, we're using to manipulate element.
Now, if you want id only for performing some operations on that input element, you don't need to get id. You can also do like this.
let elem = $('input[name="Color"]');
elem.val(''); // only if same name is not used anywhere else.
I hope this helps you.
You can use attr directly to set a value. Moreover there is no need to append #.
let element = $('[name="Color"]');
console.log("before", element.attr('id'));
element.attr('id', null);
console.log("after", element.attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="1" name="Color" maxlength="2" />
i have some html code like this
<form name="first"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
<form name="second"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
i want to select "secondText" of form "second" using jquery or javascript and i want to change value of it using jquery.
Using jQuery:
var element = $("form[name='second'] input[name='secondText']");
Using vanilla JS:
var element = document.querySelector("form[name='second'] input[name='secondText']");
Changing the value: element.val(value) or element.value = value, depending of what you are using.
To the point with pure JS:
document.querySelector('form[name=particular-form] input[name=particular-input]')
Update:
This selector will return the input named "particular-input" inside form named "particular-form" if exists, otherwise returns null.
The selector filter "form[name=particular-form]" will look for all forms with name equals "particular-form":
<form name="particular-form">
The selector filter "input[name=particular-input]" will look for all input elements with name equals "particular-input":
<input name="particular-input">
Combining both filters with a white space, I mean:
"form[name=particular-name] input[name=particular-input]"
We are asking for querySelector(): Hey, find all inputs with name equals "particular-input" nested in all forms with name equals "particular-form".
Consider:
<form name="particular-form">
<input name="generic-input">
<input name="particular-input">
</form>
<form name="another-form">
<input name="particular-input">
</form>
<script>
document.querySelector('form[name=particular-form] input[name=particular-input]').style.background = "#f00"
</script>
This code will change the background color only of the second input, no matter the third input have same name. It is because we are selecting only inputs named "particular-input" nested in form named "particular form"
I hope it's more clear now.
;)
By the way, unfortunately I didn't found good/simple documentation about querySelector filters, if you know any reference, please post here.
// Define the target element
elem = jQuery( 'form[name="second"] input[name="secondText"]' );
// Set the new value
elem.val( 'test' );
Try
$("form[name='second'] input[name='secondText']").val("ENTER-YOUR-VALUE");
You can do it like this:
jQuery
$("form[name='second'] input[name='secondText']").val("yourNewValue");
Demo: http://jsfiddle.net/YLgcC/
Or:
Native Javascript
Old browsers:
var myInput = [];
myInput = document.getElementsByTagName("input");
for (var i = 0; i < myInput.length; i++) {
if (myInput[i].parentNode.name === "second" &&
myInput[i].name === "secondText") {
myInput[i].value = "yourNewValue";
}
}
Demo: http://jsfiddle.net/YLgcC/1/
New browsers:
document.querySelector("form[name='second'] input[name='secondText']").value = "yourNewValue";
Demo: http://jsfiddle.net/YLgcC/2/
You can try this line too:
$('input[name="elements[174ec04d-a9e1-406a-8b17-36fadf79afdf][0][value]"').mask("999.999.999-99",{placeholder:" "});
Add button in both forms. On Button click find nearest form using closest() function of jquery. then using find()(jquery function) get all input values. closest() goes in upward direction in dom tree for search and find() goes in downward direction in dom tree for search. Read here
Another way is to use sibling() (jquery function). On button click get sibling input field values.
What i want to do is get the name of the hidden form which in this case is named:6ca3787zz7n149b2d286qs777dd8357b, the problem is, that form name always changes, the only thing that is the same is its value, which is 1, well 99% of the time, the only thing that is 100% the same that i guess could be somehow used to retrieve the form name is:L2ZvcnVtcy8 which is just above it. I am also attempting to do this via running javascript manually on the browser (chrome), so having that in mind where the javascript code is run through the url bar like this javascript:codegoeshere, how can i get the form name, -->(6ca3787zz7n149b2d286qs777dd8357b)?
<form action="index.php?feature=xxxxxx" method="post" name="login">
<input type="submit" name="submit" class="button" value="Logout" />
<input type="hidden" name="option" value="username" />
<input type="hidden" name="task" value="logout" />
<input type="hidden" name="return" value="L2ZvcnVtcy8=" />
<input type="hidden" name="6ca3787zz7n149b2d286qs777dd8357b" value="1" /> </form>
</li>
Check all the solutions below in this fiddle.
Some possibilities:
Assuming there is only one element with the name login and that element is the <form>, you can use:
document.getElementsByName('login')[0].getElementsByTagName('input')[4].name
If the return <input> has a fixed name attribute, then this should work (the additional .nextSibling is because there is a text node between them):
document.getElementsByName('return')[0].nextSibling.nextSibling.name
If any other of of those <input>s has a fixed name, you can use (in the example I take the <input> with name=task):
document.getElementsByName('task')[0].parentNode.getElementsByTagName('input')[4].name);
If all you really have is that fixed value, you'll have to use a for loop through all the <input>s:
var lastResortName = (function () { for(var i=0, ipts = document.getElementsByTagName('input'), n = ipts.length; i < n; i++) { if (ipts[i].value === "L2ZvcnVtcy8=") return ipts[i+1].name; } })();
Note: If there are duplicated values for the mentioned name attributes, test with the index ([0], [1], [2] and so on) until you find the expected elements.
That's really easy if you use JQuery:
$('input[type="hidden"]:eq(3)').attr('name')
Here your code running:
http://jsfiddle.net/7CHYa/
I have a form where I have to post form values to my action class. In this form I have a checkbox that needs to be readonly. I tried setting disabled="true" but that doesn't work when posting to the action class.
So please advice??
There is no property to make the checkbox readonly. But you can try this trick.
<input type="checkbox" onclick="return false" />
DEMO
<input type="checkbox" checked onclick="return false;" onkeydown="return false;"/>
http://jsfiddle.net/2srjc/
If you are worried about tab order, only return false for the keydown event when the tab key was not pressed:
<input type="checkbox" checked onclick="return false;" onkeydown="e = e || window.event; if(e.keyCode !== 9) return false;"/>
http://jsfiddle.net/2srjc/149/
You can easily do this by css.
HTML :
<form id="aform" name="aform" method="POST">
<input name="chkBox_1" type="checkbox" checked value="1" readonly />
<br/>
<input name="chkBox_2" type="checkbox" value="1" readonly />
<br/>
<input id="submitBttn" type="button" value="Submit">
</form>
CSS :
input[type="checkbox"][readonly] {
pointer-events: none;
}
Demo
I personally like to do it this way:
<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">
I think this is better for two reasons:
User clearly understand that he can't edit this value
The value is sent when submitting the form.
You may simply add onclick="return false" - this will stop browser executing default action (checkbox checked/not checked will not be changed)
Make a fake checkbox with no name and value, force the value in an hidden field:
<input type="checkbox" disabled="disabled" checked="checked">
<input type="hidden" name="name" value="true">
Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name
I use JQuery so I can use the readonly attribute on checkboxes.
//This will make all read-only check boxes truly read-only
$('input[type="checkbox"][readonly]').on("click.readonly", function(event){event.preventDefault();}).css("opacity", "0.5");
If you want the checkbox to be editable again then you need to do the following for the specific checkbox.
$('specific checkbox').off('.readonly').removeAttr("readonly").css("opacity", "1")
If you say 'No' to the following:
disable=true because other functionalities may not work, such as form posting.
onclick='return false' because other events may still trigger the
change, such as keyup, keydown when on focus.
e.preventDefault()
CSS: pointer-events: none; because you may want to allow change
under certain conditions.
Then just do this in the change event of your read-only checkbox:
$("#chkReadOnly").on("change", function () {
// Enclose with 'if' statement if conditional.
// Simply restore back the default value, i.e. true.
$(this).prop("checked", true);
});
This will solve all the above problems.
None of the above worked for me. Here's my vanilla.js solution:
(function() {
function handleSubmit(event) {
var form = event.target;
var nodes = form.querySelectorAll("input[disabled]");
for (var node of nodes) {
node.disabled = false;
}
}
function init() {
var submit_form_tag = document.getElementById('new_whatever');
submit_form_tag.addEventListener('submit', handleSubmit, true);
}
window.onload = init_beworst;
})();
Be sure to provide an appropriate replacement for the form id.
My application has a bit of context, where some boxes are pre-checked, and others you have a limit of how many of the other boxes you can check. When you hit that limit, all the non-pre-checked boxes are disabled, and if you uncheck one all the non-pre-checked boxes are enabled again. When the user presses submit all the checked boxes are submitted to the user, regardless of whether they're pre-checked or not.
In my case, i only needed it within certain conditions, and to be done easily in HTML:
<input type="checkbox" [style.pointer-events]="(condition == true) ? 'none' : 'auto'">
Or in case you need this consistently:
<input type="checkbox" style="pointer-events: none;">
You can't do it directly, but you can do it with this way I try it, and it's work fine with me at the same time it is so simple
HTML :
<input type="checkbox" checked disabled="true" class="style" />
CSS :
.style{ opacity: 1; }
Here is my solution (override) for Sencha ExtJS 7.2+ (checkbox and radio in a single override)
Ext.define('MyApp.override.field.Checkbox', {
override: 'Ext.field.Checkbox',
/**
* OVERRIDE: to allow updateReadOnly to work propperly
* #param {boolean} newValue
*
* To ensure the disabled state stays active if the field is still readOnly
* we re - set the disabled state
*/
updateDisabled(newValue) {
this.callParent(arguments);
if (!newValue && this.getReadOnly()) {
this.inputElement.dom.disabled = true;
}
},
/**
* OVERRIDE: readonly for radiogroups and checkboxgroup do not work as other fields
* https://stackoverflow.com/questions/1953017/why-cant-radio-buttons-be-readonly
*
* #param {boolean} newValue
*
* - use disabled on the field
*/
updateReadOnly(value) {
this.callParent(arguments);
if (!this.getDisabled()) {
this.inputElement.dom.disabled = value;
}
}
});
Extract from https://stackoverflow.com/a/71086058/18183749
If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :
addReadOnlyToFormElements = function (idElement) {
// html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
$('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',true);
// and, on the selected ones, to deactivate mouse/keyboard events and mimic readonly appearance
$('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');
}
And there's nothing easier than to remove these readonly
removeReadOnlyFromFormElements = function (idElement) {
// Remove the disabled attribut on non-selected
$('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',false);
// Restore mouse/keyboard events and remove readonly appearance on selected ones
$('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
}
Through CSS:
<label for="">
<input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>
pointer-events not supported in IE<10
https://jsfiddle.net/fl4sh/3r0v8pug/2/
document.getElementById("your checkbox id").disabled=true;
I am trying to create a checkbox limit based on a value change example: I have the following checkbox!
If the value of a checked checked box is different then the previous prompt an alert!
Some of the check boxes do have the same value. Not all of them!
Example:
<input name="" type="checkbox" value="here">(if this was checked)
<input name="" type="checkbox" value="here">(then this)
<input name="" type="checkbox" value="there">(would not allow prompt alert)
<input name="" type="checkbox" value="here">(would allow)
<input type="checkbox" name="checkbox2[]" onClick="setChecks(this)" value="`key`=<?php
echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>" />
I have code that limits the number of checkboxes but I'm not sure how to compare previous values to the selected.
You probably want to make use of the prev() and next() jQuery functions. I don't understand well enough what you want to do, but something like $(':checkbox').change(function() { $(this).prev(); //this references the previous sibling }) would get you started
Maybe something like
$('input:checkbox').change(function() {
if ($(this).attr('checked') && $(this).prev().attr('checked') && $(this).attr('value') != $(this).prev().attr('value')) {
alert('you can't do that');
}
});
But like I said, i don't know what you're trying to do