change labels value with javascript, when no id or class - javascript

Can you help me for changing value with javascript, but code no have id or class here is code:
<label for="flights-origin-prepop-whitelabel_en">Origin</label>
I want change "Origin" with different word.
Some examples of my code:
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
How can change this placeholder "Destination", and label text Destination?
Thanks

You can change the origin texto doing this:
document.querySelector("label[for='flights-origin-prepop-whitelabel_en']").textContent = 'New Text';

Yes, sure, you can use querySelector with label selector including for data
console.log(document.querySelector("label[for='flights-destination-prepop-whitelabel_en']"))
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>

You can find the correct element using an "attribute selector" that looks for the for attribute and a specific value for it.
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var el = document.querySelector("[for=flights-destination-prepop-whitelabel_en]");
el.textContent = "New Value";
var input = document.getElementById("flights-destination-prepop-whitelabel_en");
input.setAttribute("placeholder","New Value");
});
<button role="flights_submit" type="button">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>

The first step would be to set an array of the elements you want to target, which in this case is label. Then you would iterate through that array using a for loop to see if the textContent of that label is what you wanted to change. Finally, once you've 'hooked' the label you need, you can change the attributes for it as necessary. Please also note that textContent method is not cross browser compliant and so I've included a ternary script that will circumvent that thanks to this handy StackOverflow post .
HTML:
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>
JavaScript:
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
jsfiddle Example
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>

Related

How to make reuse JavaScript function properties using objects

I'm trying to create HTML elements and it's properties using javascript I need to reuse it in a couple of places without writing repeated same code. FYI below is my code which I'm declaring in the object.
I want to use this code for other elements which contain a label, same classes.
addNewLabels : function(){
var selectnewPwText = document.createElement('LABEL');
selectnewPwText.innerText = "Select label Name";
selectnewPwText.classList.add("mystyle");
document.querySelector('.select-new-password').appendChild(selectnewPwText);
}
var resetPasswordControls = {
passwordBtnInnerText: "Something else",
passwordBtn : function() {
return this.passwordBtnInnerText;
},
passwordHintText : function() {
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
document.querySelector(".m-hint").appendChild(para);
},
addNewLabels : function(){
var selectnewPwText = document.createElement('LABEL');
selectnewPwText.innerText = "Select label Name";
selectnewPwText.classList.add("mystyle");
document.querySelector('.select-new-password').appendChild(selectnewPwText);
}
};
// Display data from the object:
document.getElementById("btn-login").innerText = resetPasswordControls.passwordBtn();
resetPasswordControls.passwordHintText();
resetPasswordControls.addNewLabels();
<form onsubmit="return false;" method="post">
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="select-new-password"></label>
<input autocomplete="off" class="form-control required" id="Password" maxlength="20" name="Password" type="password" value="" aria-required="true">
<p class="m-hint">Must use 8-20 characters and one number or symbol.</p>
</div>
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="retype-new-password"></label>
<input type="password" class="form-control" id="password" placeholder="Enter your password">
<button type="submit" id="btn-login">Some Text need to replace</button>
</div>
</form>
You can just have your function receive the attributes as an arguments, here is an example of how you can achieve that:
var resetPasswordControls = {
passwordBtnInnerText: "Something else",
passwordBtn : function() {
return this.passwordBtnInnerText;
},
passwordHintText : function() {
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
document.querySelector(".m-hint").appendChild(para);
},
addNewLabels : function(element, innerText, className, appendTo){
var selectnewPwText = document.createElement(element);
selectnewPwText.innerText = innerText;
selectnewPwText.classList.add(className);
appendTo = appendTo || 'body';
document.querySelector(appendTo).appendChild(selectnewPwText);
}
};
// Display data from the object:
document.getElementById("btn-login").innerText = resetPasswordControls.passwordBtn();
resetPasswordControls.passwordHintText();
resetPasswordControls.addNewLabels('LABEL', "Select label Name", "mystyle", '.select-new-password');
<form onsubmit="return false;" method="post">
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="select-new-password"></label>
<input autocomplete="off" class="form-control required" id="Password" maxlength="20" name="Password" type="password" value="" aria-required="true">
<p class="m-hint">Must use 8-20 characters and one number or symbol.</p>
</div>
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="retype-new-password"></label>
<input type="password" class="form-control" id="password" placeholder="Enter your password">
<button type="submit" id="btn-login">Some Text need to replace</button>
</div>
</form>

How to create a unique id from the first two fields in the form?

I created a form with three fields first_name, Last_name, city and in the fourth field, I am having an Id column which is read-only. When the user fills the first three fields in the form, before submitting it should generate an id in the fourth column but here it should use the first two alphabets that are in the fields to generate an Id
For eg. First_name = Roid, Last_name = Steve, city = California then in the fourth field it should automatically generate this id = rostca (all the first two alphabets)
How to achieve this?
Here is a JavaScript version to answer to your issue.
(function () {
populate();
})();
function populate () {
var str = "";
Array.from(document.getElementsByClassName("inputs")).forEach(function (element) {
str += element.value.substr(0, 2).toLowerCase();
});
document.getElementById("output").value = str;
}
<div>
<input type="text" class="inputs" value="Roid" oninput="populate();" />
<input type="text" class="inputs" value="Steve" oninput="populate();" />
<input type="text" class="inputs" value="California" oninput="populate();" />
<input id="output" type="text" readonly disabled />
</div>
Here is a jQuery answer to your issue.
$(function () {
populate();
$(".inputs").on("input", function() {
populate();
});
});
function populate () {
var str = "";
$(".inputs").each(function () {
str += $(this).val().substr(0, 2).toLowerCase();
});
$("#output").val(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="inputs" value="Roid" />
<input type="text" class="inputs" value="Steve" />
<input type="text" class="inputs" value="California" />
<input id="output" type="text" readonly disabled />
</div>
Check below code,
function TextChanged(){
var first_name = document.getElementById("first_name").value;
var Last_name = document.getElementById("Last_name").value;
var city = document.getElementById("city").value;
document.getElementById("id").value = first_name.substring(0, 2) +Last_name.substring(0, 2) +city.substring(0, 2);
}
<input type="text" id="first_name" onblur="TextChanged()">
<input type="text" id="Last_name" onblur="TextChanged()">
<input type="text" id="city" onblur="TextChanged()">
<input type="text" id="id" readonly>
Check here jsbin demo, https://jsbin.com/qegazab/edit?html,js,console,output

Generating random password into input with input length using Javascript

<form name="pgenerate">
<input type="text" size=18 name="output">
<input type="button" value="Generate Password" ><br />
<b>Password Length:</b> <input type="text" name="thelength" size=3 value="7">
</form>
How can i make a random password generator that will generate password inside an input you can use in you projects or systems
var keylist="abcdefghijklmnopqrstuvwxyz123456789"
var temp=''
function generatepass(plength){
temp=''
for (i=0;i<plength;i++)
temp+=keylist.charAt(Math.floor(Math.random()*keylist.length))
return temp
}
function populateform(enterlength){
document.pgenerate.output.value=generatepass(enterlength)
}
<form name="pgenerate">
<input type="text" size=18 name="output">
<input type="button" value="Generate Password" onClick="populateform(this.form.thelength.value)"><br />
<b>Password Length:</b> <input type="text" name="thelength" size=3 value="7">
</form>
No need to reinvent the wheel. Check out this library: https://www.npmjs.com/package/generate-password which does exactly what you want.
Try this pure JS solution:
function generateRandomPassword (passwordLength) {
var outputPassword = "";
var allPossibleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < passwordLength; i++) {
outputPassword += allPossibleChars.charAt(Math.floor(Math.random() * allPossibleChars.length));
}
return outputPassword;
}
<form name="pgenerate">
<input type="text" size=18 id="output" name="output">
<input type="button" value="Generate Password" onclick="document.getElementById('output').value = generateRandomPassword(document.getElementById('thelength').value);"><br />
<b>Password Length:</b> <input type="text" id="thelength" name="thelength" size=3 value="7">
</form>
If you want to add more possible chars simply update allPossibleChars.

merge textbox values with javascript by element type

I have 3 textboxs.Their names and ids are different.I can merge their values with their names or ids but I need to merge their values with type. How can I do it.
<input type="text" id="txt1" name="textbox1">
<input type="text" id="txt2" name="textbox2">
<input type="text" id="txt3" name="textbox3">
You can get all the textbox elements by their type using document.querySelectorAll("input[type=text]").
If by merge you mean concatenating the values.
var textBoxes= document.querySelectorAll("input[type=text]");
var mergedValue;
for(var i=0;i<textBoxes.length;i++)
{
mergedValue+=textBoxes[i].value;
}
var dataVal=document.querySelectorAll('[type=text]');
var myVal="";
dataVal.forEach(function(entry) {
myVal+=entry.value;
});
console.log(myVal);
<input type="text" id="txt1" name="textbox1" value="2">
<input type="text" id="txt2" name="textbox2" value="2">
<input type="text" id="txt3" name="textbox3" value="2">
Here is another possible solution.
function mergeData() {
var textboxes = document.getElementsByTagName("input");
var mergedText = "";
for (var i = 0; i < textboxes.length; i++) {
if (textboxes[i].type === "text" ) {
mergedText = mergedText + textboxes[i].value;
}
}
document.getElementById("merged").innerHTML = mergedText;
}
<input type="text" id="txt1" name="textbox1">
<input type="text" id="txt2" name="textbox2">
<input type="text" id="txt3" name="textbox3">
<button onclick="mergeData()">Merge</button>
<div id="merged"></div>

getElementsByClassName and innerHTML

Can someone explain how to appendChild to a parent <div class="...">
and solve this ?
The innerHTML should set the variable str after every <div class='categories'> </div>
it created dynamically when you set a value to the texts and press the button "press"
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories');
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + "" + fieldValue + "" + categoryPart3;
for (var i = 0; i < newCategoryNode.length; i++) {
newCategoryNode[i].innerHTML=str;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
<script>
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategory = document.getElementsByClassName('categories');
var div = document.createElement('div');
div.setAttribute('class', 'categories');
var a = document.createElement('a');
a.setAttribute('class', 'titles');
var hr = document.createElement('hr');
var input_check = document.createElement('input');
input_check.setAttribute('type', 'checkbox');
input_check.setAttribute('class', 'check');
var input = document.createElement('input');
input.setAttribute('type', 'text');
var br = document.createElement('br');
var textnode = document.createTextNode(fieldValue);
div.appendChild(input);
div.appendChild(a);
div.appendChild(hr);
div.appendChild(input_check);
div.appendChild(textnode);
div.appendChild(input);
div.appendChild(br);
div.appendChild(br);
console.log(div);
var node = document.getElementsByClassName('categories');
for (var i = 0; i < node.length; i++) {
node[i].appendChild(div);
}
}
</script>
</html>
hope this could give you idea on how to do it.
you cannot use appendChild to a node using a string it shoud also be a DOM element
you can check on document.createElement and document.createTextNode function
hope it would help you more on your understanding
According to MDN, Node.appendChild() wants a Node object as its argument. It won't create one from a string of markup, so you'll have to create it yourself.
You can use document.createElement() to create a Node object, then you can set its innerHTML as you like. Once the Node is all set how you want, you can add it to the DOM using appendChild().
If you want to use appendChild() mehtod it doesn't work this way.First you have to create a child using element.createElement() method.Now concentrating on your code i encountered some problem. your getElementsByClassName is returning a nodelist containing all the elements having same class.So if you want to grab it provide it an index.As you have only one it's better to provide [0] index to it.
var newCategoryNode = document.getElementsByClassName('categories')[0];
if you don't provide index in getElementsByClassName() you can also access it
newCategoryNode[0].innerHTMM=str
i removed for loop from you code.If you want to use loop use for...in loop instead as it is a list of object.
var newCategoryNode = document.getElementsByClassName('categories');
for(key in newCategoryNode){
newCategoryNode[key].innerHTML=str;
}
you haven't defined checkAll() function related to one of your input tag.That surely get you an error.I've modified your code and it might give you the result you want
function addField() {
console.log('logged');
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories')[0];
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
console.log(categoryPart1);
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + fieldValue + "" + categoryPart3;
console.log(str);
newCategoryNode.innerHTML =str;
}
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onClick="addField();" value="Press">

Categories

Resources