Javascript - Select First Input (With ID) - javascript

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

Related

How to add text before input element using 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)

How to hide certain characters within an html input list?

I have an html input list, with an associated datalist, defined as follows:
<input list="mylist" id="my-input" name="friend-name"
placeholder="Begin typing friend's name here..."
required class="form-control">
The list itself (and the associated datalist) is working fine. However, each of my entries are of the form: "String [numeric_id]"
What I am wondering is if there is any way that I can somehow hide
the [numeric_id] part before the form is submitted.
I have looked at the pattern attribute, but that seems to limit the
actual data allowed in the input, which isn't what I want - I just
want the part between square brackets [] to be hidden, but still
submitted to the form.
It would be ok to move it to another input of type=hidden as well.
Is there any possible way to do that?
#isherwood, here is my form tag:
<form action="/chat_forwarding/modal_edit_msg.php" id="fwd-form" method="POST" class="form-inline" style="display: block;">
If you're not using any framework that support binding, you should listen to input events and update a hidden input based on that.
This is a function that may give you the idea:
let realInput = document.getElementById('real-input');
let userInput = document.getElementById('user-input');
userInput.addEventListener('input', function(value) {
const inputValue = value.target.value;
realInput.value = inputValue; // update the hidden input
const userInputResult = inputValue.match(/\[[^\[]*\]/); // the regex for [numberic_id]
if (userInputResult) {
userInput.value = inputValue.substring(0, [userInputResult.index - 1]); // -1 is to remove the space between the 'string' and the '[numeric_id]'
}
});
I should have mentioned that my input is also using Awesomplete (and jQuery). For this reason, binding normal events like keyup did not work (the event would fire whenever a user typed a key). I was able to achieve the functionality I wanted with the awesomplete-selectcomplete event as follows (this will add a hidden input element with value of the id from a string of the form "String [id]"):
$("#my-input").on('awesomplete-selectcomplete',function(){
var fullStr = this.value;
//alert(fullStr);
var regex = /\[[0-9]+\]/g;
var match = regex.exec(fullStr);
//alert(match[0]);
if (match != null) // match found for [id]
{
var fullName = fullStr.substr(0,fullStr.lastIndexOf("[")-1);
var x = match[0];
var id = x.substr(1, x.lastIndexOf("]")-1);
//alert(id);
$('#fwd-form').prepend('<input type="hidden" name="h_uid" value="' + id + '">');
$('#my-input').val(fullName);
}
});

How to get update all hidden fields with same name?

I have multiple hidden field with same name on html page like below
<input type="hidden" name="customerID" value="aa190809" />
I need to update values of all hidden field with same name i.e. customerID
I know how to do it(through Jquery) if html page contains single hidden field with customerID like below but not sure if there are multiple hidden field with same name
if(updatedCsrf !== null) {
var customerIDHidden = $("input[name='customerID']");
if(customerIDHidden !== null) {
customerID.val("some_value");
}
}
You can do something like this:
$("input[name=customerID]").each(function(){
this.value ="new value"
})
this will reference each DOM element. You can parse it again to jQuery DOM element by replacing this.value to $(this).val("new value") but since you only need to change the value its better with javascript vanilla
You can do that with pure JS,
var x = document.getElementsByName("customerID");
for(var i=0; i < x.length;i++){
x[i].value='new value';
}
Use jQuery each function
$("input[name='customerID']").each(function(){
$(this).val("some-value");
});

How to check element type in javascript

I have a situation in which i want to convert a <select> tag into a <input type="text"> and <input type="text"> into <select> bu using some condition.
So how can i know that this element a type text or type select using id attribute.
And also a pure javascript solution:
function toggle(a){
if(a.tagName === 'INPUT'){
a.outerHTML = '<select id="toggle"></select>';
}else{
a.outerHTML = '<input type="text" id="toggle"/>'
}
}
http://jsfiddle.net/M6qXZ/1/
2018 ES6
e => e.outerHTML = e.tagName === "INPUT" ? "<select id='toggle'></select>" : "<input id='toggle'/>"
By using
$("#inputID").attr("type");
If you alert above you will get the type of input element, then you can apply checks accordingly.
Ref here : http://api.jquery.com/attr/
UPDATE
check using
if(!$("#inputID").is("select")) {
// the input field is not a select
}
got from a link while searching not tested though.
You can use .is() to test whether the elements is of type x like
Use :text selector to test for text input element
if($("#inputID").is(":text")){
//to test for text type
}
Use element selector to test for select element
if($("#inputID").is("select")){
//to test for select
}
Get the element type using jQuery:
var elementType = $("#myid").prop('tagName');
Get the input type attribute using jQuery:
var inputType = $("#myid").attr('type');
the condicion could be for example:
if($('#whateverid').attr('type') == "text")

Place div.innerHTML as a hidden form value

I have a long page with identical section I am attempting to combine into one that has:
TITLE
description
form
I have working mouseovers that change the title and description, but need a solution to change the value of a hidden form input to the new titles when changed.
HOW do I get the hidden form value to change onmouseover to equal current TITLE.value?
Milestones
PHP
function changeContent(id, msg) {
var el = document.getElementById(id);
if (id) {
el.innerHTML = msg;
}
}
FORM
<input type="hidden" value="" name="category" />
Is this what you're looking for?
document.getElementById('hiddenInputId').value = msg;
Your hidden element doesn't have an Id, so you can use following:
var elems = document.getElementsByName('category');
elems[0].value = <<new value>>
getElementsByName always returns an array so you have to pickup first element and set its value.
Cheers !!

Categories

Resources