Set value of input html string with jquery - javascript

I have snippet of HTML in a string like this:
var htmlString = '<input type="text" id="someID" name="someID">';
How do I, with jQuery, set its value so that the HTML ends up like this:
'<input type="text" id="someID" name="someID" value="newValue">';
Thanks,
Scott

$(htmlString).attr("value", "newValue");
But this will return jQuery object, not string. You can add it to DOM.
$(htmlString).attr("value", "newValue").appendTo("body"); // you can give any element instead of body
EDIT :
You can use #idor_brad's method. That is the best way or
var htmlString = '<input type="text" id="someID" name="someID">';
var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");
console.log($htmlString.get(0).outerHTML);
or
var htmlString = '<input type="text" id="someID" name="someID">';
var $htmlString = $(htmlString);
$htmlString.attr("value1", "newValue1");
$htmlString.attr("value2", "newValue2");
$htmlString.attr("value3", "newValue3");
console.log($("<div>").append($htmlString).html());

You would first need to add your element to the DOM (ie to your web page). For example:
$(".container").append(htmlString);
Then you can access your input as a jquery object and add the value attribute like so:
$("#someID").val("newValue");
-- See Demo --

You just want to manipulate the string, right? There are a lot of ways to skin this cat, but
var newString = htmlString.replace('>', ' value="newValue">');

After the dom ready, append your input to body and then grab the input with id = "someID" and set its value to newValue
$(document).ready(function(){
$("body").append(htmlString);
$("#someID").val("newValue");
});

Related

How to createElement tag with html attributes in Javascript

I inserted an input tag after a certain element of my html source code, it seems to work, but what I need is to be able to add attributes (type, class, id etc ..) to the input tag I created.
Here is what I did in Js
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var inputCheckBox = document.createElement("input");
inputCheckBox.innerHTML = "test";
var div = document.getElementById("plugin_delete_me_shortcode_password");
insertAfter(div, inputCheckBox);
Result html
<input type="password" autocomplete="off" autofocus="autofocus" id="plugin_delete_me_shortcode_password" name="plugin_delete_me_shortcode_password">
<input>test</input> <!-- i got this as a new item -->
Now I have two problems, 1) in general the input tags don't seem to have a closing tag, but they are one line. 2) I have no idea how I could add attributes to the tag via Js.
This is what I am trying to achieve
Kindly, can someone show me the right way? I have searched some references but have not been able to find a solution. I appreciate any help, thanks.
<input type="password" autocomplete="off" autofocus="autofocus" id="plugin_delete_me_shortcode_password" name="plugin_delete_me_shortcode_password">
<input type="checkbox" class="my_class" id="my_id" onclick="my_function('example_function')"/>
You can just assign the a value to the attribute after creating the element like bellow:
var inputCheckBox = document.createElement("input");
inputCheckBox.type = 'checkbox';
inputCheckBox.id = 'the-id';
inputCheckBox.classList.add('the-class');
// for styling
inputCheckBox.style.color = 'green';
// or you can use the set attribute method
inputCheckBox.setAttribute('type', 'checkbox');
console.log(inputCheckBox);
Try to call setAttribute on inputCheckBox like`
inputCheckBox.type = 'password';
inputCheckBox.setAttribute('autocomplete', 'off');
...
inputCheckBox.name = "plugin_delete_me_shortcode_password";
You can use DOM for Vanilla JavaScript
const element = createElement("div");
div.setAttribute("data-custom-attribute", "custom-value");
If you want to use JQuery:
$('<div></div>').attr({
id: "my-id"
})
More on this on the official documentation

getElementByID.onchange not working after i update html with = innerHTML

My starting html looks like this:
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
and i have a variable that captures the html:
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
Then I have an onchange operator that performs a couple functions when the first row has text in it. the .onchange is picked up fine the first time and the subsequent functions are run. I end up with an additional row:
for (n = 1; n < inputLength+1 ; ++n) {
var test2 = document.getElementById(dude+n);
test2.onchange = forFunction
}
function forFunction() {
for (m = 1; m < inputLength+1 ; ++m) {
var test = document.getElementById(dude+m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder="+dude+(m+1)+" id="+dude+(m+1)+" name="+dude+(m+1)+"><br>";
document.getElementById('group_names').innerHTML = updateHTML(txt);
//function updateHTML(txt)
}
}
}
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
function updateHTML(txt) {
html = html + txt;
return html;
}
The issue is that after all that completes i end up with two input rows as desired: name1 and name2. However, when i enter text in those fields for a second time, the .onchange is not picked up. but the elements are there in the html when i inspect and view the html.
Also, when i
console.log(inputFormDiv.getElementsByTagName('input').length);
the length of the inputs increases from 1 to 2 after i first run functions (upon the first time i change the value in my input field) so that is getting recognized correctly, just not the .onchange.
thoughts?
The onchange will only work if added to the attribute on the html and the user clicks out of a textbox e.g:
<input onchange="forFunction()" type="text" class="form-control name" placeholder="name1" id="name1" name ="name1">
To add the onchange event in JavaScript code. Add the change event to the addEventListener e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('change', forFunction, false)
However if you want the event to fire whilst the user is types a key then use the keypress event. e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('keypress', forFunction, false
A basic example: https://jsfiddle.net/xrL6y012/1/
Instead of .innerHTML = html + text do .insertAdjacentHTML('beforeend', text), that way you keep the original html (and events binding).
Edit: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
I had the same problem, it seems like modifying the HTML will never work, regardless of how you do it (.innerHTML or .insertAdjacentHTML()).
The only way that worked for me is to append a child instead of editing the HTML, like so:
const span = document.createElement('span');
span.innerHTML = 'text and <b> html stuff </b>';
initialElement.appendChild(span);
And if you actually need to insert just pure text, then this works:
initialElement.append('just text');
Hope that helps.

How to replace the value attribute in an HTML string?

Given:
let mystr = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";
I'd like to remove the text in the value param "Luis Tiant" using JS.
To be clear: I want to change value="Luis Tiant" to value="" in the string itself. This is a string not yet a DOM element. After I remove the value then I'll add it to the DOM.
Get the input element and set its value to '' (empty string).
Example below clears the input value after 2 seconds, so you can see it in action:
setTimeout(() => {
document.querySelector('input').value = '';
}, 2000);
<input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="Luis Tiant">
Update
Question above has been clarified. If you'd like to replace the value attribute in the string itself you can accomplish that using regex and the replace method like so:
let string = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";
console.log(string);
let newString = string.replace(/value=\".*\"/, "value=\"\"");
console.log(newString);
By initializing the ID you can do this as well.
document.getElementById("item_Name").value = "Your new Value Here";
Instead of setting a variable equal to a string of html, then using string manipulation to change the element attributes, I'd suggest using the Document.createElement() method and related APIs to programmatically create the html element. Then you'll have access to methods like Element.removeAttribute()
let mystr = "<input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="Luis Tiant">"
var res = mystr.match(/value=\".*\"/g);
var str = mystr.replace(res, 'value=""');

Add element works but clears input value

I have a script below that adds an element to my form, another text input field. It adds the new text input field but if I type something into the first one then add a new field it removes the input text from the first one.
I cant see where im going wrong here, im fairly new to JavaScript so please go easy :)
function addAnother() {
var id = 1;
var elemebt = document.getElementById('quest');
var number = elemebt.getElementsByTagName('*').length;
var add = number + 1;
var element = '<input type="text" name="question[]" id="quest'+ add +
'" placeholder="Example: What previous experiance do you have?" class="form-control" id="cloan"><a id="name'+
add +'" onClick="removeEle('+ add +')">Remove</a>';
document.getElementById('quest').innerHTML += element;
}
In JavaScript, the following two statements are practically identical:
str = str + ' more text ';
str += ' more text ';
The key point here is that in the end, the value of str is COMPLETELY OVERWRITTEN.
In your case, that means the innerHTML of the "quest" element is overwritten and the browser completely recreates it's children nodes, thus reseting any state and input values.
To overcome this, you can use the appendChild method but you first need to create the element to append. The easiest way to do that given you have a string of your HTML is to inject that string into a dummy element using the innerHTML property:
var target = document.getElementById('target');
var tDiv = document.createElement('div');
var htmlString = '<input type="text"></input>';
tDiv.innerHTML = htmlString;
target.appendChild(tDiv.children[0]);
<div id="target">Keep my content safe!</div>

Grab the value of latest textbox on a particular variable having multiple textbox with same ID

I want the value of last textbox to be grabbed by the varialble on multiple textbox with same ID.
HTML
<input type="text" id="get"><br>
<input type="text" id="get"><br>
<button id="grab">Click</button><br>
SCRIPT
$("#grab").click(function(){
var value = $("#get").val();
});
Or, a way to delete the first textbox might also work. Working Example
Your HTML is invalid: HTML elements can't have the same id attribute.
Use the class attribute, instead.
You can then use .last() to get the last element that matches the .get selector:
$("#grab").click(function(){
var value = $(".get").last().val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="get" value="foo"><br>
<input type="text" class="get" value="bar"><br>
<button id="grab">Click</button><br>
(I added the value attributes for demonstrative purposes. Obviously, they can be removed.)
If you want to get the first element's value if the second one is empty, you could do this:
$("#grab").click(function(){
var firstValue = $(".get").val(); // `.val()` gets the first element's value by default
var secondValue = $(".get").last().val();
var result = secondValue || firstValue;
alert(result);
});
If you don't have any control on ids you should use following solution. If you can change the ids you should change them.
You approach will not work because the id is not unique. It will always get the first input.
$("#grab").click(function() {
// var value = $(this).prev("input").val(); // Will work when there is no `<br>`
alert($('input[id="get"]').last().val());
});
Here $('input[id="get"]') will get all the elements having id get and last() will get the last element from it.
Demo: https://jsfiddle.net/orghoLzg/1/

Categories