I'm not really a programmer, but I have to change some html/css/js code for our needs.. and I'm struggling.
we are using a cloud software, which closed source, but with the possibility to change parts of the HTML frontend.
the software uses the CSS class "dom-admin" to hide some setting for non-admin.
<div class="dom-admin"> hidden for non-admins </div>
if a user logs in, the display property is set by the system to display:none;
.dom-admin {
display: none;
}
these hidden fields are mostly input fields. we dont want to hide this fields for our users, we just want to set the fields readonly.
my idea is to read the display value within a javascript in a if / else query:
if (dom-admin('display') == 'none')
{ document.write('<input type="text" id="XX">') }
else
{ document.write('<input readonly type="text" id="XX">') }
My Problem is to access the display value, i tried x examples from the net, but i never able to read the property of "dom-admin", eg:
document.getElementById('dom-admin').style.display
Chrome Javascript Console:
Uncaught TypeError: Cannot read property 'style' of null
Chrome dev-tools shows me this about the "dom-admin" CSS:
I appreciate any help...
Thanks, Patrick
Phase 1: Reveal All Hidden Field(s)
Multiple Elements with Common ClassName
The class .dom-admin is merely presentational, it is not a security measure. If you want to access multiple elements with the className of dom-admin you must collect them into a NodeList/HTMLCollection:
var DOMObjects = document.querySelectorAll('.dom-admin');
OR
var DOMObjects = document.getElementsByClassName('dom-admin');
With this list you'll have to iterate/loop through each *.dom-admin by a for loop, or array method (if the latter them the list might need to be converted to an array):
for (let i=0; i < DOMObjects.length; i++) {...
OR
DOMObjects.forEach(function(DOMObj, index) {...
To reverse the style of .dom-admin, you can set each *.dom-admin style object to:
DOMObj.style.display = "block"
OR remove .dom-admin class:
DOMObj.classList.remove('dom-admin')
Single Element with ClassName
The most direct method is to target the className via querySelector() or getElementsByClassName()[0]:
var DOMObj = document.querySelector('.dom-admin');
OR
var DOMObj = document.getElementsByClassName('dom-admin')[0];
Phase 2: Set All Revealed Fields to be Non-editable
Set/Get/Change Element Attributes
id, class, readOnly, etc. are called attributes. The attribute needed has a Boolean value (true/false). An attribute such as readonly merely needs to exist on the tag in order for it to be true. Not actually be in the tag of course makes it false.
Set an attribute
More specifically, adding an attribute to an element when it didn't exist before:
DOMObj.setAttribute('readonly', true);
Get an attribute
Finding an attribute and reading the value of said attribute:
DOMObj.getAttribute('readonly');
Change an attribute
If the attribute already exists and the value needs to be changed:
DOMObj.removeAttribute('readonly')
Keep in mind that the attribute you are dealing with has a Boolean value so it is handled differently than an attribute with a String value.
DOMObj.setAttribute('name', 'foo'); /*OR*/ DOMObj.name = "foo"
DOMObj.getAttribute('name');
DOMObj.setAttribute('name', 'bar') /*OR*/ DOMObj.name = 'bar'
Note 1
The syntax for methods querySelector()/querySelectorAll():
document.querySelector('.dom-admin')
CSS Selector ===========^-----^[dot for class]
is different than the syntax of method getElementsByClassName():
document.getElementsByClassName('dom-admin')
DOMString====================^------^[no dot needed]
document.getElementsByClassName('dom-admin')[0]
DOMString====================^------^===^-^[no dot needed]==
[Bracket Notation with index of zero is needed if there is only one target]
Note 2
Do not use document.write unless you intend to destroy everything on your page.
If you have inputs nested within the div.dom-admin, that would mean that those inputs exist already but the user cannot see them. It isn't necessary to create them and even if you do need to create any element, never use document.write. Instead use createElement() or use innerHTML on an element that you intend to use as a container.
Demo
// Collect all .dom-admin into NodeList
var das = document.querySelectorAll('.dom-admin');
// forEach() .dom-admin, remove the class .dom-admin
das.forEach(function(da, idx) {
da.classList.remove('dom-admin');
// Find all inputs in the div formerly known as .dom-admin
var inputs = da.querySelectorAll('input');
/* forEach() input nested within the div formerly known
|| as .dom-admin, set its attribute readonly to true
*/
inputs.forEach(function(input, index) {
input.setAttribute('readonly', true);
});
});
.dom-admin {
display: none;
}
input {
font: inherit;
width: 40%
}
<div class="dom-admin">
<input type='text' value='These inputs exist already'>
<input type='text'>
</div>
<div class="dom-admin">
<input type='text' value='Do not use document.write'>
<input type='text' value='it will overwite EVERYTHING'>
<input type='text' value=''>
</div>
<div class="dom-admin">
<input value='Fun fact:'>
<input value='input by default is type="text"'>
<input>
</div>
Here's what I used to achieve what you want.
As others mentioned, use document.querySelector('.dom-admin') to access the class and when you change display style, you can use the if statement
let admin = document.querySelector('.dom-admin');
if (admin.style.display === 'none') {
document.write('<input type="text" id="XX">');
} else {
document.write('<input readonly type="text" id="XX">');
}
.dom-admin {
width: 200px;
display: none;
}
<div class="dom-admin">
<form action="#">
<input type="text" id="user" />
<input type="number" id="user_number" />
<input type="password" id="user_password" />
<input type="submit" id="submit" />
</form>
</div>
Related
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
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
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/
so I've got this form:
<form id="imageinputpopup" class=suggestionsubmit style="display: none">
<span>Add a thing!</span><br/>
<label>url: </label><input name="imageurl" type="url"><br/>
<label>file: </label><input name="imagefile" type="file"><br/>
<input type='hidden' name='schoolid' class="schoolid">
<input type="submit" value="Submit">
</form>
and this click handler:
$(".allow-submission").live('click', function(){
if($(this).attr('inputtype')=="colorpicker"){
....
} else if($(this).attr('inputtype')=="image"){
remove_hidden("#imageinputpopup");
add_fieldname($(this), $("#imageinputpopup"));
$("#imageinputpopup").dialog();
} ....
});
remove_hidden looks like:
function remove_hidden(element){
alert($(element).children('.fieldname').length);
$(element+'.fieldname').remove();
alert($(element).children('.fieldname').length);
}
and add_fieldname looks like:
function add_fieldname(element, addto){
var elementname = document.createElement('input');
elementname.type = 'hidden';
elementname.name = 'fieldname';
elementname.value = element.attr('fieldname').replace(' ', '_');
$(elementname).addClass('fieldname');
addto.append(elementname);
}
as I expect, with each click, a tag like this is added:
<input type="hidden" name="fieldname" value="mascot_image" class="fieldname">
but remove_hidden isn't removing!
I know the selector is right because the alert is exactly the number of these input tags, but they're just not getting removed. Why? I also tried $(element+).remove('.fieldname'); and that didn't work either.
In this line of remove_hidden
//Select the element with the id of element AND has the class of fieldname
$(element+'.fieldname').remove();
Try putting a space before the . like so:
//Select the children of element which have a class of fieldname
$(element+' .fieldname').remove();
EDIT: Added comments above to clear things up a bit
If I get this source right, on one hand you don't have an ID on the input you get when you add a fieldname with the add_fieldname function. You might want to set that for ease of use.
On the other hand, in the remove_hidden function you alert out the element .fieldname, but trying to remove the element.fieldname (notice the missing space in front of the class name), so I presume you need this in the remove_hidden function:
$(element+' .fieldname').remove();
I hope it helps.
try replacing
$(element+'.fieldname').remove();
with
$(element+' .fieldname').remove();
It's because .remove([selector]) "filters the set of matched elements" to decide what to remove.
Their documentation threw me off at first. What you are trying to remove already needs to be in the collection (no selector in the remove method would remove the entire collection).
Ex: Remove input.fieldname:
$(element).find('.fieldname').remove('.fieldname');
or (for the larger case collection case):
$(element).find('input').remove('.fieldname');
Ex: Do NOT remove input.fieldname:
$(element).find('input').remove('.notfieldname');
I have 4 jquery radio buttons in my form something like this
<form:radiobutton path="lcmoption" name ="lcmoptions" id ="lock" value="lock" checked="checked"/>
<fmt:message key="lcm.form.options.lock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="unlock" value= "unlock"/>
<fmt:message key="lcm.form.options.unlock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="terminate" value="terminate" />
<fmt:message key="lcm.form.options.terminate" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="wipe" value="wipe" />
<fmt:message key="lcm.form.options.wipe" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="other" value="other" />
<fmt:message key="lcm.form.options.other" />
onclick of the first four radio buttons I am dynamically loading the select box using an AJAX call. When the user clicks the last option, i.e, other, I need to hide the textbox and show a text area.
I tried using:
$("input:radio[name=lcmoption]").click(function() {
if(type=="other")
{
$([name="reasonsList"]).css("display",none");
$([name="otherreasonsList"]).css("display", "block");
}
else
{
// AJAX CALL to load dropdown (for other options)
}
}
But this did not work. I also tried:
$([name="reasonsList"]).hide();
$([name="otherreasonsList"]).show();
This shows both the dropdown and text area. Can anyone help me on hiding reasonsList div and show otherreasonsList div onclick of a radio button with other value?
There's all kinds of syntax errors in the code you posted.
For instance, you need to quote your selector strings as text, and an attribute value in an attribute selector ([name=something]) can be either an unquoted single word or a quoted string.
In this case, just leave it out:
$('[name=reasonsList]').show();
Also, instead of $.click(), I would use $.change(), which will detect when the radio value has changed.
$("input:radio[name=lcmoptions]").change(function(){...});
See notes in comments:
// First line looks ok, but I would use a .change() handler
// Also, I just noticed you're:
// "input:radio[name=lcmoption]"
//
// But shouldn't it be:
// "input:radio[name=lcmoptions]"
//
// See lcmoptions vs lcmoption (no s on second); it's lcmoptions
// in your template code. I don't know what path="lcmoption" means,
// but I think name="lcmoptions" is what you need to use to select.
$("input:radio[name=lcmoption]").click(function() {
// What is type? I think you mean this.value or $(this).val()
// Don't forget to lowercase the comparison, so other matches
// Other.
if (this.value.toLowerCase() == "other")
{
// The selector needs to be quoted as a string, ie:
// '[name="reasonsList"]'
//
// Also, jQuery has a shortcut method, $(sel).hide();
$([name="reasonsList"]).hide();
// The same thing here, you need to quote that string or
// alternatively, since it's a single word, leave the quotes
// out of the selector, ie:
// $('[name=otherreasonsList]')
//
// Again, jQuery has a shortcut method, $(sel).show();
$('[name=otherreasonsList]').show();
}
// Don't know if you missed this in the example, but you need });
// to close the $.click() function.
});
And your second attempt:
// Same problem as above, you need to quote the string for the
// selector, ie:
// $('[name=reasonsList]')
//
// With inner quotes, but here they're unnecessary.
$('[name="reasonsList"]').hide();
//
// Without inner quotes on name value
$('[name=otherreasonsList]').show();
For what you're wanting to do, you can:
$(document).ready(function(){
// This is called caching, which is a good practice to get
// get into, as unless you need to requery due to dynamic
// changes, selecting them only once and reusing will give
// you better performance.
var $lcmoptions = $('input:radio[name=lcmoptions]'),
$textbox = $('[name=textbox]'),
$textarea = $('[name=textarea]');
$lcmoptions.change(function(){
// Note I this.value.toLowerCase() the comparison value
if (this.value.toLowerCase() === 'other') {
$textbox.hide();
$textarea.val($textbox.val()).show();
} else {
$textarea.hide();
$textbox.val($textarea.val()).show();
}
});
});
For more information on caching, see:
Does using $this instead of $(this) provide a performance enhancement?
This is assuming your client-side markup looks something like:
<input type="radio" name="lcmoptions" id="unlock" value= "lock"/> Lock
<input type="radio" name="lcmoptions" id="unlock" value= "unlock"/> Unlock
<input type="radio" name="lcmoptions" id="terminate" value="terminate" /> Terminate
<input type="radio" name="lcmoptions" id="wipe" value="wipe" /> Wipe
<input type="radio" name="lcmoptions" id="other" value="other" /> Other
<div>
Enter text:
<input type="text" name="textbox" value="test text stuff"/>
<textarea name="textarea"></textarea>
</div>
http://jsfiddle.net/LthAs/
Have tried this mine working fine
if(document.getElementById('other').checked==true)
{
$("#txtboxID").hide(350);
$("#txtareaid").show(350);
}
try this, u can put this on change event or click event.
if ($("radio[#name='lcmoptions']:checked").val() == 'other')
$("#otherreasonsList").show();