Changing an html "for" label with java script - javascript

I need to change a "for" label from an extension using javascript. I am unsure how to do this.
Thank in advance for the help!
<input id="theCheckboxId" type="checkbox" name="theCheckBoxName" />
<label for="theCheckBox">The text I want to change</label>

DEMO
First give the label an id
<label id="lbl1" for="theCheckBox">The text I want to change</label>
then do
document.getElementById("lbl1").setAttribute("for", "theCheckboxId");
EDIT
Wait, did you want to change the for value, or change the actual text of the label? In any event, here's how you would change the text:
if (label.textContent)
label.textContent = "New Text";
else if (label.innerText)
label.innerText = "New Text"
else
label.innerHTML = "New Text";

You didn't ask, but if you are using jQuery, you can do it a bit simpler via:
$('label[for="theCheckBox"]').text('your new text')
That said, the advice of giving it an ID instead is definitely the most performant option, though we don't know if you have access to the HTML or not (as if you did, you could probably just change the text right there)

To change the text, do this:
document.getElementById('theCheckboxId').nextElementSibling.textContent = 'newValue';
or this:
document.querySelector('#theCheckboxId + label').textContent = 'newValue';
Or if you need to support older browsers, do this:
function nextElement( el ) {
while( (el = el.nextSibling) && el.nodeType !== 1 );
return el;
}
nextElement( document.getElementById('theCheckboxId') ).innerHTML = 'newValue';
http://jsfiddle.net/3kEYw/

Related

Selecting iOS-Keyboard when input is created by javascript

When creating an input by javascript, mobile safari does not choose the right keyboard. For first input the decimalPad-keyboard is shown, but for second input only the numbersAndPunctuation-keyboard is shown.
How can I fix this?
let myInput = document.createElement('input');
myInput.id = 'second';
myInput.type = 'number';
myInput.min = '0';
myInput.step = 'any';
myInput.inputmode = 'decimal';
document.getElementById('here').appendChild(myInput);
first input: <input id='first' type='number' min='0' step='any' inputmode='decimal'>
<div id='here'>second input: </div>
Instead of using :
myInput.inputmode = 'decimal';
use this:
myInput.setAttribute('inputmode','decimal');
OR
myInput.inputMode = 'decimal'; // uppercase M
Explanation:
In general the "DOM attributes" for html nodes are usually written in camelCase if you use javascript! Inside the HTML you will use the "alllowercase" version. "DON'T ASK WHY. ;-)". But it is more recommended to use setAttribute() method on nodes because this will always end up in an DOM element attribute no matter what ever you writin'

Javascript - Select First Input (With ID)

I am writing a script with pure JS and need to select a text input from a page that has a random name each time:
<input type="text" name="N8PkpWeLsNRQBjvwcwKULB57utJx5L2u0Ko" class="form-control" value="">
Normally i would select it using ID like:
var textinput = document.getElementById("myInput1");
There is no ID however, how can i select this element?
As far as i can see it appears to be the only text input on the page.
I planned on setting some text like this:
HTMLInputElement.prototype.setText = function(text) {
this.value = text;
};
var el = document.querySelectorAll('input[type=text]')[0];
el.setText("Hi");
But this does not work for some reason?
You can use document.querySelector(selectors) it returns the first matching element within the document.
document.querySelector('input.form-control[type=text]')
HTMLInputElement.prototype.setText = function(text) {
this.value = text;
};
var textinput = document.querySelector('input.form-control[type=text]');
textinput.setText("Hi, You can no use setText method.");
<input type="text" name="N8PkpWeLsNRQBjvwcwKULB57utJx5L2u0Ko" class="form-control" value="">
To get the first text field use the following.
var txtField=document.querySelectorAll('input[type=text]')[0];
To set the text you could simply do.
txtField.value="your Value";
This way you can select any HTML tag , since you only have 1 input, this should work for you
var input = document.getElementByName('input');
Try this
var x = document.getElementsbyClassname("form-control").getAttribute("value");

dhtmltooltip with text in an array

I'm trying to use dhtmltooltip with texts for tips in an array.
HTML :
<div id="div0">This div is tooltipped using the script<br />
wished tooltip = Paris.<br />
</div>
<br />
<div id="div1">
This div is tooltipped using the script<br />
wished tooltip = London.
</div>
<div id="dhtmltooltip"></div>
Script :
I = new Array();
I[0] = "Paris";
I[1] = "London";
for (var num=0; num<I.length; num++)
{
mytext = I[num];
div = document.getElementById('div'+num);
div.setAttribute("onmouseover", "ddrivetip(mytext)");//FF and IE>8
div.setAttribute("onmouseout", "hideddrivetip()");//FF and IE>8
}
I use the dhtmltooltip script found here.
The problem is that the second tip (London) is used for both tips.
It must be a trivial error but I can't find it.
You can see a test file here.
Could someone help me ?
Thanks
First of all, all of these variables are globals and that in itself is probably causing you an issue.
But your actual problem is here:
div.setAttribute("onmouseover", "ddrivetip(mytext)");
Change it to this
div.setAttribute("onmouseover", "ddrivetip('" + mytext + "')");
The problem is two-fold. Firstly, mytext is a global var when you probably want it to be local. This isn't causing trouble now but mark my words, with this sort of thing it'll bite you. The other problem is that you're not attaching events properly. Change this:
div.setAttribute("onmouseover", "ddrivetip(mytext)");
to this:
div.onmouseover = 'ddrivetip("' + mytext + '")';
Or better yet, use closures and addEventListener.

Use RegEx and .replace to substitute text with user input?

I'm new to jQuery and stumbled on the concept of RegEx with .replace to make nifty text replacements.
In my form, I have some checkboxes that trigger text to appear in a textarea. There are also some user input areas as fields.
How can I use this jQuery to substitute a portion of text in certain checkboxes with the user input, but not in others? I figure using an if/else argument to trigger the RegEx and replace is key, but I don't know how to incorporate the rest?
Here is a mockup of my form:
<div style="width: 500px;"><br>
Static options:<br>
<label id="_comLine100"><input id="comLine100" name="comLines" type="checkbox"> OPTION1 </label> <br>
<label id="_comLine101"><input id="comLine101" name="comLines" type="checkbox"> OPTION2 </label> <br>
Options which can be modified by user text:<br>
<label id="_comLine102"><input id="comLine102" name="comLines" type="checkbox"> OPTION3 </label> <br>
<label id="_comLine103"><input id="comLine103" name="comLines" type="checkbox"> OPTION4</label> <br>
</div>
<br>
<input id="usrinput1" size="50" placeholder="Enter something to replace the word Text">
<br><br>
<form>
<input onclick="javascript:this.form.outPut2.focus();this.form.outPut2.select();"
value="Select all" type="button">
EDIT Here is my new script, based on suggestions below:
$(document).ready(function(){
var comLines = {
comLine100: 'Text for option1 \n',
comLine101: 'Text for option2 \n',
comLine102: 'Text for option3 \n',
comLine103: 'Text for option4 \n'
};
var mytextbox = document.getElementById('outPut2');
var chosenComm = null;
var Inputs = document.getElementsByName("comLines");
for (var i = 0; i < Inputs.length; i++) {
Inputs[i].onchange = function() {
chosenComm = this;
printComment();
};
}
function printComment(){
if(chosenComm !== null){
var chxbox=chosenComm.id;
var uinput = document.getElementById('usrinput1');
if(uinput.value!=="" && (chxbox=="comLine102" || chxbox=="comLine103")){
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
else {
mytextbox.value += comLines[chosenComm.id] + "\n";
// resets the radio box values after output is displayed
chosenComm.checked = false;
// resets these variables to the null state
chosenComm = null;
}
}
}
});
See my JSfiddle : http://jsfiddle.net/bENAY/2/
Now works as I wanted. Thanks to Eric S for the explanations and guidance!
The simple answer is replace:
mytextbox.value += comLines[chosenComm.id] + "\n";
with
mytextbox.value += comLines[chosenComm.id].replace(/Text/, $('#usrinput1').val()) + "\n";
The replace call looks for the regex in the slashes and replaces the match with the value after the comma.
$('#usrinput1').val() is using jQuery to find the dom element with ID of usrinput1 and then getting the value of it (since it's an input, it gets whatever the user has entered).
The more complete answer would mention that you probably should embrace jQuery more:
Replace the window.onload call with a $(document).ready(function(){...}) call.
Consider replacing the document.getElementById with $('#outPut2')
Consider replacing the document.getElementsByName with $(input[name=commLines]) or adding a class of comm-lines to all of those items and using $(.comm-lines)
Consider using jQuery's on function to bind the event handlers for both the inline button handlers (use a passed in function to the on call) and the Inputs[i].onchange calls.
Sorry if this sounds overly judgmental, just trying to suggest a more standard and less error-prone solution.
Still requires some tweaking, but something along the lines of this:
$('.comm-lines').on('change', printComment);
Also, I'm sure this is just a simplified example of what you're trying to accomplish, but you might consider using links or buttons instead of checkboxes. Your use of checkboxes doesn't really follow the expected experience your users have learned when using checkboxes on the web. A link more closely matches the experience most users know, and so provides less surprise to them. (Less surprise means happier users, less learning on their part and more usage.)

Javascript change label's text via innerhtml not working

I have this javascript function:
function validateFile() {
var file = document.getElementById('fuCSV');
if (file.value == "") {
document.getElementById('<%=lblStatus.ClientID%>').innerhtml = "Please select a file to upload. Client!";
return false;
}
else {
document.getElementById('<%=lblStatus.ClientID%>').innerhtml = "";
return true;
}
}
Its called on the Button's OnClientClick event like this:
<asp:Button ID="btnImport" runat="server" Text="Import" OnClientClick="return validateFile();" CausesValidation = "true"
UseSubmitBehavior ="true" OnClick="btnImport_Click" />
I'm trying to change the text of the label lblStatus on validateFile() method, but the text is not changing. However, while debugging...QuickWatch shows the changed value. What might be the cause for it? how can I resolve this?
I had suggested to use innerText but apparently, the W3C-compliant way of doing this is to use textContent:
document.getElementById('<%=lblStatus.ClientID%>').textContent = "Please select a file to upload. Client!";
See Mozilla's documentation here.
Use correct casing on the property: innerHTML
http://www.tizag.com/javascriptT/javascript-innerHTML.php
Javascript is case sensitive, if you set innerhtml property instead of innerHTML you won't see anything.
var e = document.getElementById("fName_err");
e.innerHTML = "** Enter first name";
get the id where you want to give output in e.

Categories

Resources