HTML:
<input type="text" id="inputsNum" />
<div id="content"></div>
jQuery:
$("#inputsNum").bind('change paste keyup', function () {
var count = $(this).val(),
content = "";
for (var i = 0; i < count; i++)
{
content += $(this).append($('<input>').prop('type', 'text'));
}
$(this).next().html(content);
});
Hi,
want to let the user to add multiple text inputs based on value he provided
i wrote the above code but i'm getting [object Object] error repeated actually based on the value i provided , means its working but why its doesn't append the text inputs !
need your help
thank you
Here is the working JS Fiddle
$(document).ready(function() {
$("#inputsNum").bind('change paste keyup', function () {
var count = $(this).val(),
content = "";
for (var i = 0; i < count; i++)
{
content += '<input type="text" />';
}
$('#content').html(content);
});
});
You can try replacing content += $(this).append($('<input>').prop('type', 'text')) with content += "<input type='text' />";
The append function that you are using returns an object and not the HTML as string like you expect it to. Thus when you add it as a string, the toString() method of the object converts it to [object Object] and that gets appended to your HTML
Related
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
I want to create n number of textboxes dynamically based upon the user input.
Each textbox must populate with a serial number.Here, what I have tried so far.
function generateSerial(sender,eventArgs){
debugger;
//var rw_Serail = stockin.rw_Serail;
if(eventArgs.get_newValue()!="0"){
if(eventArgs.get_newValue()!=eventArgs.get_oldValue()){
create(eventArgs.get_newValue());
//OpenWindow(null,null,"rw_Serial");
}
}
}
Create will call a function and it's job is to create textboxes and assign a value.
function create(param) {
debugger;
var s= "";
for(var i = 0; i < param; i++) {
s+= `<input type="text" style="width:72%" name="txtSerial" value=${generateLicense()}>`
`<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML
}
document.getElementById("dvserialNo").innerHTML=s;
}
as name suggests generateLicense() will return a serial number..
function generateLicense() {
return "abcd1234Etc..";
}
Now while running this code, I am getting this error..
In chrome
Uncaught TypeError: generateLicense(...) is not a function
In firefox
TypeError: (("<input type=\"text\" style=\"width:72%\" name=\"txtSerial\" value=" + (intermediate value)) + ">") is not a function
Note: I want to create and assign it's value at the same time.
Concatenate the two elements in s+. And, of course, as one of the answers suggested include quotes for value="${generateLicense()}"
s+= `<input type="text" style="width:72%" name="txtSerial" value="${generateLicense()}">`
+ `<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML
I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a scenario like
for(int i = 0; i < 10; i++)
{
<input type = "text" id="test"+i value="" onchange="getValue(i)">
}
I want to print selected text box value using jquery. I tried below code,....
function getValue(id)
{
var value = $("#test"+id).val();
alert(value);
}
Some how the above code is not working.
if i tried like var value = document.getElementById("test"+id); then it is working.
jsBin demo
var inp = ''; // String will hold all inputs
for(var i=0; i<10; i++){
inp += '<input type="text" id="test'+i+'" value="" />'; // Generate 10 inputs
}
$('body').append( inp ); // All inputs to HTML
$('input[id^="test"]').on('input', function(){
console.log( this.value );
});
You can't just drop raw HTML inside of a JavaScript loop like that. You have to set a string or create an element and append it to the DOM.
"getValue(i)" is a string. The "i" is not the variable i, it is literally a string with the letter i. If you want to concatenate strings and variables you have to do so like this:
var name = "Neil";
var greeting = "Hi, my name is " + name + ", nice to meet you!";
I have a some problem
i.e i have a 60 text box controls in asp page i want to text box text to empty so , i am using like below
var st = document.getElementById("<%=hiddenrate.ClientID%>").value;//Total Control names
var controlnames = st.split(','); //split with comma
var i = 0;
for (i = 0; i <= controlnames.length; i++)
{
var gh = '' + '.SetText(' + "'Empty text'" + '' + ');';
ft[i] + gh;
//example rate1.SetText('');
rate2.SetText('');
'
'
rate60..SetText('');
}
but in javascript is that control name and property
How to set text as empty in total controls dynamically?
Thanking You,
Rajesh
IF you want to clear the values of all text inputs use this code:
// get all <input> elements
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// check input type
if (inputs[i].type === 'text') {
inputs[i].text = '';
}
}
You could easily modify that code to handle textareas as well or add some more filtering to the elements.
If you consider using JS framework you can make this code much shorter. For example if you use jQuery then here's the code for you:
$(document).ready(function () {
$('input:text').text('');
});
Here is another sample to clear value all textboxes:
<script type="text/javascript">
function pp(){
for(p in form1.childNodes) {
if(form1.childNodes(p).type=="text")
form1.childNodes(p).value="";
}
}
</script>
<body>
<form name="form1">
<input type="text" name="a1"/>
<input type="text" name="a2"/>
<input type="text" name="a3"/>
<input type="button" name="a11"/>
<input type="submit" name="a12"/>
<input type="button" value="Clear" onclick="pp()" name="a13"/>
</form>
</body>
How about simply calling document.forms["form1"].reset() in Javascript? It will clear the values of all the controls in the form.
Thanking u all i got the solution like below method
var i = 0;
for (i = 0; i <= ft.length; i++) {
x = new Object();
x = ft[i];
propertyName = ".SetText";
propertyValue = " ";
if(x !="undefined")
eval(''+x+'' + propertyName + "('" + propertyValue + "');");
or
eval(x).SetText('');
}
thnks to all.