Clear multiple textbox using JavaScript on button click - javascript

I working in Asp.net c#. I have a task to clear multiple textbox on button click, but now according to the requirement I have to use JAVASCRIPT. So I can't do that with C# code.
Now I am using the following :
JAVASCRIPT Function :
function clrCtrl() {
document.getElementById('TextBox1').value = "";
}
with this method the line of is greater. Now when I have 20 30 of textbox this code is not efficient so plz give me any suggestion to this....

Give class name to the text box to which you want to clear then try to use
document.getElementsByClassName("MyTestClass") to get elements and use your logic to do whatever you want.
eg:-
function clrCtrl() {
var elements = [] ;
elements = document.getElementsByClassName("MyTestClass");
for(var i=0; i<elements.length ; i++){
elements[i].value = "" ;
}
}
Hope this helps.
Kind Regards.

Have you considered using JQUERY? Jquery selectors has different combinations that may help you to more easily reset controls based on CSS classes, control types, using 'likes'.
http://api.jquery.com/button-selector/
Here is an example from jquery page:
<input class="myClass" name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
$( ".myClass" ).val("setting value based on class")
</script>

if you are using jQuery you could add a style class like textbox to each of your textboxes and then do $('.textbox').val('');
you html would look something like
<asp:TextBox runat="server" ID="TextBox" CssClass="textbox" /> for each of you text boxes make sure to include CssClass="textbox"

You should gather the input elements you want to clear first, and then just loop on them to erase their content :
function clrCtrl() {
var elems = [] ;
elems = elems.concat(document.getElementsByTagName("input"));
elems = elems.concat(document.getElementsByTagName("textarea"));
//and so on
for(var i=0,c=elems.length ; i<c ; i++){
elems[i].value = "" ;
}
}
I would also advice to give a common className to those elements if you want to group them :
function clrCtrl(groupName) {
var elems = [] ;
elems = elems.concat(document.getElementsByTagName("input"));
elems = elems.concat(document.getElementsByTagName("textarea"));
for(var i=0,c=elems.length ; i<c ; i++){
if(elems[i].className==groupName){elems[i].value = "" ;}
}
}
Or if you are targetting only modern browsers, you can use the "getElementsByClassName" method :
function clrCtrl(groupName) {
var elems = document.getElementsByClassName(groupName) ;
for(var i=0,c=elems.length ; i<c ; i++){
elems[i].value = "" ;
}
}

<html>
<head>
<script>
function funClear() {
document.getElementById("form1").reset();
}
</script>
</head>
<body>
<form id="form1">
Name:<input type="text" id="txt"><br><br>
Email:<input type="text" id="txt"><br><br>
Phone:<input type="text" id="txt"><br><br>
Message:<input type="textarea" height="50" width="70" id="txt"><br><br>
<input type="button" name="clear"value="clear" onclick="funClear()">
</form>
</body>
</html>

Related

JavaScript changing value of custom attribute by searching another custom attribute

thanks for reading.
So the input tags don't have an ID or a class name.
The value attribute is also custom.
This is what I was trying.
HTML
<input name="password" data-value="">
.
#"var aTags = document.getElementsByTagName('input');
var searchText = 'password';var found;
for (var i = 0; i < aTags.length; i++)
{
if (aTags[i].textContent == searchText){found =
aTags[i].setAttribute('data-value','123456789');
alert(found.getAttribute('data-value')); break;}
}");
or
var myInput=$('input[data-value='']').setAttribute('data-value','12345678');
alert(myInput.getAttribute('data-value'));
I tried using get elements by name, but there is nothing showing. As I think there may be multiple results. And I want a safer solution.
well thanks everyone, I didn't expect such a great response.
I was interested to see how this would be solved, but apparently the following line works
aTags[i].value='123456789';
I suppose anything with the word value is seen as a value field if the exact 'value' attribute can't be found.
Thanks flash, attr might work for this also I suppose.
var myInput = $('input[name="password"]').setAttribute('data-value','12345678');
alert(myInput.getAttribute('data-value'));
Try this
Since you are using jQuery already you can use the attr() method to get the value of the specified attribute.
var myInput = $('input[data-value]').attr("data-value","12345678");
console.log(myInput.attr('data-value'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-value="">
var myInput = $('input[name="password"]').attr('data-value','12345678');
alert(myInput.attr('data-value'));
Try something like this
I hope it will help.
const setAttribute = (attr, val) => input => {
return input.setAttribute(attr, val)
}
window.addEventListener("load", () => {
const searchValue = "1231"
const selector = `input[value='${searchValue}']`;
const inputs = Array.from(document.querySelectorAll(selector));
inputs.map(setAttribute("data-value", "1231231"))
})
<input value="1231" />
<input value="1231" />
<input value="aaa" />
with jQuery you can access the data attributes directly, but you must cycle through them as there may be more than one:
$.each($('input[data-value='']'),function(){
$(this).data('value','12345678');
});
or, if the input field is just one, use an id:
<input type='password' id="pwd" data-value="" />
and
$('#pwd').data('value','12346578');
<input /> is a self closed element so it will not have textContent attribute. But, yes, in some browsers it will work if you type <input>text content</input>, but in others it won't work.
What i recommend is to keep that value in an attribute right on the input. Follow the example bellow.
Documentation:
About textContent: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
Self Closing elements: https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
<input type="text" data-textcontent="password"/>
JS
var aTags = document.getElementsByTagName('input');
var found;
var searchText = 'password';var found;
for (var i = 0; i < aTags.length; i++)
{
console.log(aTags[i].getAttribute('data-textcontent'));
if (aTags[i].getAttribute('data-textcontent') == searchText){
aTags[i].setAttribute('data-value','123456789');
found = aTags[i].getAttribute('data-value');
break;
}
}
console.log(found);

Javascript select all HTML input fields with array style name

I have a form that I am building and would like to have a javascript to select and manipulate all of the fields that are within the named array:
<input type="text" name="location[street]" value required />
<input type="text" name="location[city]" value required />
<input type="text" name="location[zip]" value required />
<input type="text" name="location[state]" value required />
How can I build a selector for javascript to toggle all of the elements disabled state?
Jquery is possible but not preferred. I would prefer a method that would work without libraries - such as document.getElementsByName().
I believe that querySelectorAll doesn't have support for a selector to get an element by an attribute, like jQuery would be input[name^="location"](docs). So, try this:
var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].name.indexOf("location") > -1)
{
els[i].disabled = true;
}
}
Fiddle. I will be glad to hear that I'm wrong and there is a way for doing this only using a selector.
Anyway, you can use the fieldset and make your code more semantic by disabling only the fieldset, if you like: Fiddle.
UPDATE
In order to disable all textarea and select elements as well, just include those tags on the selector:
var els = document.querySelectorAll('input, textarea, select');
Fiddle
Alternative to queryselector would be getElementsByTagName
var i;
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; ++i) {
var name = inputs[i].getAttribute("name");
if(name.indexOf("location") > -1)
{
inputs[i].disabled = true;
console.log(name);
}
}
link to JSFIddle

How to clear and replace the contents of an input field with the value of a button?

I think there is an easy solution however I have searched and cant seem to find he answer. I am trying set up several buttons that when pressed replace the the contents of an input field with the value of the button. I would prefer to control this with pure javascript rather than jquery if possible.
Also, if possible I would like the title of the button to be slightly different than the value it passes to the input field.
One way to do it
script:
function foo(id, el)
{
document.getElementById(id).value = el.innerHTML.replace(/test/, 'something');
}
(Obviously you'd want to do something more useful to the value than replacing test by something. But you can.)
html:
<input id="piet"/>
<button onclick="foo('piet',this)">test123</button>
<button onclick="foo('piet',this)">test234</button>
http://jsfiddle.net/sE2UV/
Assume this markup (an extra data attribute to avoid hardcoding the selector):
<input id="target" type="text">
<button value="potatoes" data-for="#target">Potato</button>
<button value="tomatoes" data-for="#target">Tomato</button>
You may use value attribute to store the data:
var buttons = document.querySelectorAll('button[data-for]');
for (var i = 0; i < buttons.length; i++) {
var targetId = buttons[i].dataset.for;
var target = document.querySelector(targetId);
buttons[i].addEventListener('click', function () {
target.value = this.value;
})
}
Demo: http://jsfiddle.net/dmu8N/
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function setText() {
document.getElementById("input1").value = "SOME TEXT";
}
</script>
</head>
<body>
<button type="button" onclick="setText()">Click me to set text!</button>
<input id="input1" type="text">
</body>
</html>
Full JSBin Example: http://jsbin.com/aZIyAzir/2/
Here's a jQuery solution for completeness.
<input type='text' id='target'></input>
<button>Merry</button>
<button>Christmas</button>
Then your jQuery:
$(function() {
var $target = $('#target');
$('button').on('click', function() {
$target.val($(this).html());
});
});

How do I get the first child of each of these rows?

I have 2 rows, each with 2 text inputs. How do I go through each row w/ class "myRow" and, within each row, get the first child that has class "This"? I can get the first "This" class of row 1 but can't seem to get row 2.
My fiddle
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btn').click(function(){
$(".myRow").each(function(){
var r = $(".This").eq(0).val();
alert(r);
});
});
});
</script>
</head>
<body>
<div class="myRow">
<input type="text" class="notThis" value="wrong!"/>
<input type="text" class="This" value="first one!"/>
<input type="text" class="This" value="almost!"/>
</div>
<br>
<br>
<div class="myRow">
<input type="text" class="notThis" value="wrong!"/>
<input type="text" class="This" value="second one"/>
<input type="text" class="This" value="almost!"/>
</div>
<button id="btn">Submit</button>
</body>
</html>
$('#btn').click(function(){
$(".myRow").each(function(){
var r = $(".This:first", this).val();
alert(r);
});
});
$('.This:eq(0)','.myRow').css('background-color','#F00');
$('.myRow').find('.This:eq(0)').css('border-color','#F00');
$('.This:first','.myRow').css('color','#0F0');
$('.myRow').find('.This:first').css('font-weight','bold');
Working example
$('#btn').click(function(){
$(".myRow").each(function(){
var r = $(".This", this).eq(0).val();
alert(r);
});
});
To get both in a selector, you could always do:
var elems = $('.This:eq(0)', '.myRow');
Then you could do this to get an array of the values:
var values = $.map($('.This:eq(0)', '.myRow'), function(el) {return el.value});
FIDDLE
Change to:
Demo
var r = $(this).find(".This").eq(0).val();
You need to look for .This relative to the current element, otherwise it will always find the first instance.
Side note: as an alternative to .eq(0) you can use .first().
You can get an array of JavaScript objects by using jQuery's factory method to search for a certain property. Example:
var search = $('input[class="This"]');
You can access the first one found by simply using:
search[0];
Essentially (and this is not the most optimized way of doing it), you can do this:
var rows = $('.myRow');
for(var i = 0; i < rows.length; i++) {
var first;
var row = $(rows[i]);
var children = row.find('input[class="This"]');
// You can also do row.find('input.This');
if(children.length > 0) {
first = children[0];
// Do something with it
}
}
Like I said, not the most optimal way, but each time you use the factory method, you're getting an array of objects and you can loop through them.
You can search through HTML properties like the above.
Examples:
$('input[type="button"]')
$('input[name="firstName"]')
$('a[href="www.google.com"]')
This should do the trick:
$('#btn').click(function(){
$(".myRow input:nth-child(1)").each(function(){
alert($(this).val());
});
});

Retrieving the value of Dynamically Created elements

i Have created a HTML form , in this form when i Click on a button it creates input text fields based on a predefined criteria , this works fine .
now when i try and retrieve the value entered in those created text fields using alert i am not able to do so .
i have two questions
What is the best way to retrieve inputs from the dynamically created text fields?
can you tell me why the code i have written does not work
HTML code
<BODY>
<FORM>
<BR/>
<div align = "center">
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
</div>
<div align="center" id="d_div">
<form name="permavalues" id="d_form">
</form>
<br/> <br/>
</div>
</FORM>
THe javascript code that i am using is this :
function getkeywords() {
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
add(splitresult[i-2]);
}
}
}
The add function which is called in getkeywords:
function add(s) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", s);
element.setAttribute("name", s);
element.setAttribute("id", s);
var foo = document.getElementById("d_form");
//Append the element in page (in span).
foo.appendChild(element);
alert("Value=" + document.getElemebtById(s).value);
}
I think that i must have a mistake with element.setAtrribute("id",s);
The major problem is you can't put form inside another form. Please remove you HTML code line 2 and line 13.
Another problem is your typo, as IvanL said.
Other code are fine.
Give you fully tested work code as below.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>test</title>
<script language="javascript">
function getkeywords() {
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
add(splitresult[i-2]);
}
}
}
function add(s) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", s);
element.setAttribute("name", s);
element.setAttribute("id", s);
var foo = document.getElementById("d_form");
//Append the element in page (in span).
foo.appendChild(element);
alert("Value=" + document.getElementById(s).value);
}
</script>
</head>
<BODY>
<BR/>
<div align = "center">
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
<br><br><br>
<input type="button" value="add" onclick="add('tt')">
</div>
<div align="center" id="d_div">
<form name="permavalues" id="d_form">
</form>
<br/> <br/>
</div>
</body>
</html>
What is the best way to retrieve inputs from the dynamically created
text fields?
I would use JQuery to traverse the form for all text input elements and retrieve their respective values.
Alternatively, you could give each of the text fields a common name like "txt_" and then append an incremental ID to the string (I.E. -- txt_1, txt_2, txt_3, ...) then programmatically iterate over your form fields that match until you've reached a value that represents the total number of available form fields. That value could be a javascript integer.
For example...
$("form input[type='text']").each( function()
{
// gets text value for each field in the form
var textFieldValue = this.value;
// do stuff
});
Have a look on the Jquery code for getting All Input Value.
$(document).ready(function()
{
$('form#d_form input[type="text"]').each(
function()
{
alert($(this).val());
});
});

Categories

Resources