change controlname dynamically in javascript - javascript

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.

Related

javascript capture every value in a div

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"

Pull first instance of input and add id via JS

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>

Print dynamic Text box value using JQuery

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

Add line break to HTML from Js loop

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \n escape character, but it didn't do anything. Any help would be appreciated.
function generateIDs()
{
var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;
}
<form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>
<p id="numbers">
</p>
\n doesn't mean much to a browser; use <br/> instead.
Example:
// snip
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id.toString() + '<br/>';
}
//snip
Note that this is going to overwrite the previous value on each iteration. You probably want this:
par.innerHTML += id.toString() + '<br/>';

Populating anchor link from several textfields

I try to populate several textfields to become something like this Check
Below is my script that I modified from here but this script is only show inside textarea and how to show inside anchor link and generate something like Check.
<div id="textBoxContainer">
<input type="text" id="name" onkeyup="UpdateTextArea();" name="name" />
<input type="text" id="group" onkeyup="UpdateTextArea();" name="group" />
</div>
<textarea id="textAreaResult"></textarea>
Check
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + "&";
}
textAreaFinalResult.value = finalResult;
}
</script>
If you want to target an anchor tag instead of the textarea, then obviously you need to change that accordingly:
<a id="hrefResult" href="check.php">link</a>
Then in your updateTextArea function, you need to target the anchor's href rather than the textarea's value. There's several other optimizations that can be made in there also, such as making an array of name/value pairs and then doing a join on them so you don't end up with the trailing &, etc.
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var length = textboxes.length;
var target = document.getElementById("hrefResult");
var params = [];
var baseref = 'check.php';
for (var i = 0; i < length; i++) {
params.push(textboxes[i].id + "=" + textboxes[i].value);
}
target.href = baseref + '?' + params.join('&');
}
What the heck, here's a fiddle of the whole thing.
It would probably make sense to change the name of the function itself since there's no textarea involved anymore, but I leave that as something for you to do.

Categories

Resources