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

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());
});
});

Related

Jquery Not working to create new Inputs

Below is my Html Doc and the JQuery does not do anything when the range input changes, any assistance is much appreciated as I am extremely new to web design. Even the alert doesn't work at the top so I am unsure as to what my problem is. My belief is somehow the script is never being called or it's a problem with it being an html doc but either way thank you.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var num=0;
var numOptions = new Array(100);
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
$(document).ready(function(){
$("#numQuestions").on('input',function(){
var numbQuestions = $("#numQuestions".text());
if(num>numbQuestions){
for(i=numbQuestions;i<=num;i++){
try{
$("#qRowNum'+i).remove();
}catch(err){
}
}
}else{
for ( i=num; i < numbQuestions; i++)
{
var row = '<div id="qRowNum'+ i '">
#the below function is not implemented in this version
<input type="text" placeholder="Question '+i'"> <input type="range" name="numOptions'+i'" min="0" max="5" placeholder="Number Of Options" onchange="CreateOptions(this);" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();> </div>';
$("#questionRows").append(row);
//New script test
}
}
num = numbQuestions;
});
});
<div id="questionRows">
</div>
<input type="submit" value="Start">
</form>
</body>
</html>
This is your problem:
var numbQuestions = $("#numQuestions".text());
Firstly I think you mean this:
var numbQuestions = $("#numQuestions").text();
But that is also not true because an input field has not text property. They have value So do this:
var numbQuestions = $("#numQuestions").val();
And this is another problem: $("#qRowNum'+i) When you start selector by double quotation, you need to end this also by double quotation. But it still is not a true jquery selector.
I think you need to more studies about jquery.

Clear multiple textbox using JavaScript on button click

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>

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());
});
});

Build, Modify, Output Javascript Array

I'm trying to accomplish the following...if it's asking too much in a single question then some simple steps on what events to use will still help.
There are 2 blank textareas sitting next to eachother - Input and Output. Between them are two inputs Before and After. I want to type or paste a list of words into Input separated by line break, for example:
melons
peaches
apples
And then use the Before and After inputs to add in a word/phrase/symbol before and after each keyword. So if I type 'buy' in before and 'today' in after, the Output text area will display:
buy melons today
buy peaches today
buy apples today
I'd like to accomplish this without having any page refreshing. We can assume the form elements are named as follows:
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
I've been try to at least get the Input text to display in Output using this code, but that's not even working:
$(document).ready(function(){
$('#input').keyup(function(e){
$('#output').html($(this).val());
});
});
Any guidance would be awesome!
a compact one:
$("#input,#before,#after").on("keyup", function () {
$("#output").val(
$.map($("#input").val().split("\n"), function (n, i) {
return $("#before").val() + " "+ n + " " + $("#after").val();
}).join("\n"));
});
example
This would do the trick:
function update_output(){
//Split input by newline
var input_words = $('#input').val().split('\n');
var output_lines = new Array();
//Iterate over each keyword and prepend and append values
$.each(input_words, function(i, word){
output_lines.push($('#before').val()+' '+word+' '+$('#after').val());
});
//Display output in textarea
$('#output').val(output_lines.join('\n'));
}
You just need to choose when you want to update the output textarea, maybe bind it so it updates every time the #input or #before and #after changes:
$('#input,#before,#after').on('change',update_output);
Alright, I can help you to get started. My answer is not complete, but you can have a very good idea from here. Note I wrote this code to be easy to understand and I am not using sophisticated approaches on purpose.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#input").keypress(function(key){
if(key.which == 13) {
refreshData();
}
});
});
function refreshData() {
var beforeVal = $("#before").val();
var inputLines = $("#input").val().split(/\r\n|\r|\n/g);
var desiredOutputVal = "";
for(var i=0; i<inputLines.length; i++) {
desiredOutputVal += beforeVal + inputLines[i] + "\n";
}
$("#output").val(desiredOutputVal);
}
</script>
</head>
<body>
<form>
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
</form>
</body></html>

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