How to add text before input element using JavaScript? - javascript

item1:<input type="text" name="item1">
I want to add the text "item1" before the input element in JavaScript.How can I do that?
I have created an input tag in JavaScript using
var i1 =document.createElement("input");

You can use insertAdjacentHTML.
document.querySelector('input').insertAdjacentHTML('beforeBegin', "item1: ");
<input type="text" name="item1">
If you are creating the element dynamically, first append it to an element like the body, and then use insertAdjacentHTML.
var i1 = document.createElement("input");
document.body.appendChild(i1)
i1.insertAdjacentHTML('beforebegin', "Item: ");

Use input.insertAdjacentHTML('beforeBegin', 'HTML'). This code inserts HTML before the start of the input element.
const input = document.querySelector('input')
input.insertAdjacentHTML('beforeBegin', 'item1: ')
<input type="text" name="item1">
MDN Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

This code finds all the input in the document with name attributes and prepends the name text in front of the input:
document.querySelectorAll("input[name]").forEach((input) => {
input.insertAdjacentHTML('beforeBegin', `${input.name}: `);
});
<input type="text" name="item1"><br>
<input type="text" name="item2"><br>
<input type="text" name="item3">

You can create an element, like this
let input = document.querySelector("input")
let element = document.createElement("YOUR DESIRED ELEMENT GOES HERE")
element.insertBefore(input)

Related

How to select "input type" value dinamically created through JS

When i got an HTML page which has a form like this
<form name='form'>
<label>Title <input id = "larger_title" type='text' maxlenght="100" name='ticket_title' value=''></label>
i select its value by using
const form=document.forms['form'];
form.addEventListener('submit',create);
...
form.ticket_title.value
But when i do create an input type element through JS, so dinamically, for example as if i have an array of elements, each of them with a button that enables a function where are sent data that includes these input text, how do i select the values of these like i used to with form, but now without a form, straight from js itself?
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.value="";
This code is outside the function related to the button, but how do i select its values in the function?
How should i select the text inserted in the input area whenever the user submits the button?
Interacting with a dynamically created element is no different than interacting with a static one - - you access its properties and methods the same way.
Your problem is that although your code to create a new dynamic element isn't actually inserting the element into the document, so although it exists, it can't be found in the DOM. It should be appended to the document first:
const form=document.forms['form'];
form.addEventListener('submit',create);
function create(event){
form.ticket_title.value;
form.post_solution.value = "TEST";
}
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.value="";
// Now, insert the element into the document
document.querySelector("form > div").appendChild(input);
<form name='form'>
<div>
<label>Title <input id = "larger_title" type='text' maxlenght="100" name='ticket_title' value=''></label>
</div>
<button>Submit</button>
</form>
But, accessing your form fields through the use of document.forms[] is quite ancient and really should be retired and instead use the modern .querySelector() instead. .querySelector() accepts any valid CSS selector as a way of locating the first matching elment.
document.querySelector("form").addEventListener('submit',create);
function create(event){
form.ticket_title.value;
form.post_solution.value = "TEST";
}
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.value="";
// Now, insert the element into the document
document.querySelector("form > div").appendChild(input);
<form name='form'>
<div>
<label>Title <input id = "larger_title" type='text' maxlenght="100" name='ticket_title' value=''></label>
</div>
<button>Submit</button>
</form>
First you add an id or class property to the input:
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.id = "myInput";
input.value="";
Then you use document.getElementById:
const input = document.getElementById('myInput');
input.addEventListener('onchange', handleChange);

Clear and sendkeys using javascript selenium

I have a question text field. When I click on it display:none for h3 appears and for input tag dissappears. Then I can clear field and enter new name.
<td style="width:92%;">
<h3 id="question_text_1846" onclick="return onClickQuestion(1846,'text');">test name</h3>
<input type="text" id="question_text_input_1846" onkeypress="return OnKeyPress(event, 1846,'text');" name="question_text_input_1846" onblur="return onBlurQuestion(1846,'text');" placeholder="Question Text" value="test" class="form-control myInput" style="display:none;" />
<script type="text/javascript">
$("#question_text_1846").html(unescape($("#question_text_1846").html()));
</script>
</td>
The question is how to set new name(clear field and sendkeys) through selenium and may be javascript manipulations. I tried to use several methods , but it doesn't work.
element = driver.findElement(By.xpath("//h3[#id='question_text_"+ExtractQuestionTextInputID()+"']"));
actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
element.click();
element = driver.findElement(By.xpath("//input[#id='question_text_input_"+ExtractQuestionTextInputID()+"']"));
element.clear();
element.sendKeys("test_question_one");
And also with js
String qtid = "question_text_" + ExtractQuestionTextInputID();
String qtiid = "question_text_input_" + ExtractQuestionTextInputID();
js.executeScript("document.getElementById("+qtid+").setAttribute('style', 'display: none;')");
js.executeScript("document.getElementById("+qtiid+").setAttribute('style', '')");
This is the method for extracting id from tag attribute
public String ExtractQuestionTextInputID(){
String question_text_input_id = driver.findElement(By.xpath("//input[#value='New Question']")).getAttribute("id");
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(question_text_input_id);
String mid = new String();
while(m.find()) {
//System.out.println(m.group());
mid = m.group();
}
return mid;
}
I'm not sure if I understand it correctly but did you try setting attribute 'value' of the input to an empty string?

How do I set the value of a text input field when the field does not have an id but it has a name. I can't use document.getElementById

I am try to set the value of an input field for which i can not assign an ID so I can't use document.getElementById. Is there any other way I can assign a value to this text input field that has a name?
You can use a basic queryselector to select attributes and to do so, you need to put the attributes name between brackets [ and ]. The attributes can have an optional value too by using an equal sign.
Here is a working example:
document.querySelector('[name=hello]').value = 'Hello World'
<form>
<input type="text" name="hello">
</form>
Use document.getElementsByName: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
const el = document.getElementsByName('name')[0];
el.value = 'someValue';
You can use Document.getElementsByname().
This method returns an array of elements, so you might want to access the first element in the array.
Live Example:
var myInput = document.getElementsByName("my-input")[0];
myInput.value = "Some Text";
<input type="text" name="my-input">
If the input field, named 'x', for example, is in a form with name 'f' for example, then:
document.f.x.value = 'some value';
function test()
{
document.f.x.value = 'It works!';
}
<html>
<body>
<form name="f">
<input name="x" size="20">
<br>
<input type="button" value="Test" onclick="test();">
</form>
</body>
</html>

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");

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.

Categories

Resources