JavaScript get element through parent - javascript

...
<td id="mycell">
<input type="text" name="year" onmouseout="do_something(this.value,...);" />
<input type="text" name="month" onmouseout="do_something(this.value,...);" />
</td>
...
i need to get value of neighbouring input element when submitting function on other element.
Thing is there are 10 of them and i cannot use id, names are same as well.
So i need to somehow get parent <td> and then address its child e.g. i submit year then onmouseout="do_something(this.value, this.parent.td.month.value");"

If you have a reference to one of the input elements, then:
var td = input.parentNode;
And you can then select all child input elements using:
var inputs = td.getElementsByTagName('input');
And to get a particular one:
var input0 = inputs[0];
and so on. To get an adjacent input, find the current input in the inputs collection, then grab the next or previous (if there is one) as required.

use the .next and .previous selector:
$(this).previous('input').val();
$(this).next('input').val();

Related

JQuery: How to select label of input's ancestor

I have the following HTML:
<div class="control-group">
<label class="control-label-sub">Description/Pack Size</label>
<div class="controls">
<input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />
<label id="packetSize-error" class="form_error" for="packetSize">
This field is required.
</label>
</div>
</div>
Is there a way to select the <label> element that is the child of .control-group (ie, the one with "Description/Pack Size" text), from the <input /> text field in my HTML?
To select the <label> element that is above the <input/> element, you could:
first use .closest() to select the first .control-group above the <input/> element and then
select the first child label of that .control-group
This can be achieved via the following jQuery script:
const input = $('input[name="packetSize"]');
const controlGroup = input.closest('.control-group');
const label = $('label', controlGroup);
It's possible to condense this into a single line but I've broken it into steps for clarity. Hope that helps.
If you want to get all label that class was named "control-label-sub".
var element = $("label.control-label-sub")
And If you want to get only that label I prefer following
var element = $("input#packetSize").parent().prev()

Javascript - Associating a label with an input using javascript

I have a webpage with lots of inputs. They are all in this format, with the input tag before the label.
<input type='checkbox' id='myinput'>
<label for='myinput'>My Text</label>
Using javascript, if I didn't want to type type='checkbox' each time, I could do this, and each input would become a checkbox...
for (i=0;i<document.getElementsByTagName('input').length;i++) {
document.getElementsByTagName('input')[i].setAttribute('type', 'checkbox')}
I'd like to do the same thing with the label element. I don't want to use for='myinputsID' for every label. I realize I can nest the inputs inside the label like this to eliminate the for,
<label>My Text
<input type="checkbox" id="myinput">
</label>
but lets just say I don't want to do that. I need to keep the html in the same format with the input first and then the label... I would need to find a way to apply the htmlFor attribute to each label and assign it the ID of the input immediately preceding it. Is that possible?
Basically you have to use document.getElementsByTagName("input") to get a collection of all the input html elements on your page. Afterwards loop over this list to see which of those are actually checkboxes. If we found a checkbox, we can get the next html element using element.nextElementSibling. Finally just set the htmlFor attribute for those to the id of the input element.
var elements = document.getElementsByTagName("input");
for (var a = 0; a < elements.length; a++) {
if (elements[a].type == "checkbox") {
elements[a].nextElementSibling.htmlFor = elements[a].id;
}
}
<input type='checkbox' id='myinput1'>
<label>My Text</label>
<input type='checkbox' id='myinput2'>
<label>My Text</label>
<input type='checkbox' id='myinput3'>
<label>My Text</label>
I think this should work
var inputs = document.getElementsByTagName('input');
var input;
for (i=0;i<inputs.length;i++) {
input = inputs[i];
input.setAttribute('type', 'checkbox');
input.nextElementSibling.setAttribute('for', input.id);
}

How to control related text input element with a button?

I have a list of text-field + button that gets rendered dynamically. The user hits the button and I want to control the input field when a button is clicked.
I figure you could do something like:
<input id="1"><button onclick="doSomething(1)">Something</button>
<input id="2"><button onclick="doSomething(2)">Something</button>
<!--...-->
<input id="3"><button onclick="doSomething(3)">Something</button>
But wonder if there's a different and more sophisticated solution because the code I'm modifying passes an an anonymous function to onclick and I can't pass a unique ID like the method above.
This is very easy to achieve in vanilla Javascript (as most things). No jQuery overhead required here.
let buttons = [...document.getElementsByClassName('inputbutton')]
function doSomething(i) {
console.log(i);
}
for (const button of buttons) {
button.addEventListener('click', (e) => {
const i = e.target.previousSibling.id
doSomething(i);
})
}
<input id="1"><button class="inputbutton" type="button">Something</button>
<input id="2"><button class="inputbutton" type="button">Something</button>
<!--...-->
<input id="3"><button class="inputbutton" type="button">Something</button>
If you modify your dynamic HTML like the following and add this jQuery, you will be able to access the value of the previous input field.
var buttons = $(".inputs-and-buttons #button-after-input-field");
buttons.click(function() {
console.log($(this).prev("input").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs-and-buttons">
<input id="1" value="1"><button id="button-after-input-field">Something</button>
<input id="2" value="2"><button id="button-after-input-field">Something</button>
<!--...-->
<input id="3" value="3"><button id="button-after-input-field">Something</button>
</div>
You can generate dynamic Id for both input field and button with index or row number or you can add custom attribute for row number as below.
You can generate dynamic related control with specific Id for textbox and button as well. e.g. txtFirstName_1, txtLastName_1, btnAdd_1. here textbox and button distinguished by its id and number after Underscore "_" .
$(function(){
// Register click on button
//here you can pass specific class name for button if all are have same functionality
$("button").click(function(e){
console.log(this);
var btnId=$(this).attr("id");
//console.log(btnId);
// Way 1
//Split btnId with "_" e.g btn_1 will splited with ["btn","1"]
var rowIndex=btnId.split("_")[1];
console.log(btnId.split("_"),rowIndex);
$("#txt_"+rowIndex).val("Upate value by btn"+rowIndex); // Or fetch value
// Way 2
// You can directly use custom attribute data-row and do your work
var rowIndex1=$(this).attr("data-row");//$(e).prop("data-row");
console.log(rowIndex1);
//$("#txt_"+rowIndex1).val("Upate value"); // Or fetch value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txt_1" data-row="1"><button id="btn_1" data-row="1">Something</button>
<input id="txt_2" data-row="2"><button id="btn_2" data-row="2">Something</button>
<input id="txt_3" data-row="3"> <button id="btn_3" data-row="3">Something</button>

find element html with jquery

how to find element html with Jquery .
in this example element html is "input"
jsfiddle
$("#her").click(function() {
var $t = $('#mee');
console.log($t.filter());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mee">
<input type="submit" value="click ici" id="her">
$(this).prev().prop('nodeName');
I believe this was the JSFiddle link - http://jsfiddle.net/sr2o412y/
<input type="text" id="mee">
<input type="submit" value="click ici" id="her" >
If you want to select a element using jquery you can use (#)id attribute or (.) class attribute or (input) html tagname.
In this case if you want to take the data from text element which has id => "#mee" on click if id => "#her". You can use the below code
$('#her').on('click', function(){
var textvalue = $('#mee').val();
console.log(textvalue);
});
Provide readable id and class names to identify elements properly.
Your selectors looks fine to me. In short, you can use any valid CSS selector, so both $('#her') and $('#mee') should be working in your example, as you have HTML elements with those ids:
$('#her').click(function() {
var $t = $('#mee');
console.log($t.val());
});
<input type="text" id="mee" />
<input type="submit" id="her" value="SUBMIT" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you want to select an element based on its type (tag) instead, then just remove the #. For example, to select any input element on the page you would just do:
$('input')
Or, to get just the first one:
$('input').first()
Or also:
$('input').eq(0)
You can also select elements based on type plus attribute to select specific inputs:
$('input[type="text"]')

How to find an element within another element without an id

I am trying to change the values of some input element when a value of select dropdown changes.
When the select dropdown changes, i want to change some hidden textbox and a normal textbox which are with a td with class="owner".
Within the td tag there are multiple elements with type="hidden" and one input type= text. I want to change the values of element with type="hidden" and id ending with _lkid and _lkold and then the only element within the td which is of type="text" and is within a span tag
I don't have an id of the elements within the td as they are generated automatically nor can i assign a class to those elements. i can only assign class to the td.
I am able to change the values of hidden text, but i am unsure of how to change the type="text" field. Any pointers would be helpful.
Jsfiddle : https://jsfiddle.net/4honph7n/3/
This js is probably not the best/effective code written, taking some baby steps with jquery
HTML
<select class="selectClass">
<option>Option 1</option>
<option>Option 2</option>
</select>
<table>
<tr>
<td class="owner">
<select>
<option>1</option>
<option>2</option>
</select>
<input type="hidden" id = "someid_lkid" value="00590000002BIF7">
<input type="hidden" id = "someid_lkold" value="Some Text">
<!-- there are some more hidden fields -->
<span class="lookupInput">
<input type="text" id = "someid" value="Some Text">
</span>
</td>
</tr>
</table>
Js
$(document).ready(function () {
$('.selectClass').change(function() {
$('.owner').each(function(i) {
$(this).find("input[type='hidden']").each(function(){
if($(this).attr('id').indexOf("lkid") > -1){
$(this).val('new id');
alert($(this).val());
}
if($(this).attr('id').indexOf("lkold") > -1){
$(this).val('new text');
alert($(this).val());
}
})
})
})
})
If you want to assign the same text/value to all inputs then
$(document).ready(function () {
$('.selectClass').change(function () {
$('.owner input[id$="lkid"]').val('new id');
$('.owner input[id$="lkold"]').val('new text');
$('.owner input:text').val('new val');
})
})
Demo: Fiddle
You can use the attribute ends with selector:
var $lkid = $(this).find("input[id$='_lkid']"),
$lkold = $(this).find("input[id$='_lkold']"),
$text = $(this).find("input:text");
You can use .find() with class selector along with child selector and Attribute Ends with selector
var textInput = $(this).find('.lookupInput input');
alert(textInput.val());
//Similarly you can use
var lkid = $(this).find("input[id$='_lkid']");
var lkold = $(this).find("input[id$='_lkold']");
DEMO
You can use the following selectors.
select hidden input with id containing 'lkid':
$('[id*=lkid]')
select hidden input with id containing 'lkold':
$('[id*=lkold]')
select text input:
$('td.owner>span.lookupInput input[type=text]')
Try this: DEMO
$(document).ready(function () {
$('.selectClass').change(function() {
$(".owner input[id$='_lkid']").val('new id');
$(".owner input[id$='_lkold']").val('new text');
$(".owner span input[type=text]").val('new value');
})
})
You just need to use some selectors for that like,
To get all inputs -> $("input")
To get all inputs with type attribute -> $("input[type]")
To get all hidden inputs -> $("input[type=hidden]")
To get all inputs with type ends with 'den' -> $("input[type$=den]")
To get all inputs with type starts with 'hid' -> $("input[type^=hid]")
To get all inputs with type contains 'idd' -> $("input[type*=idd]")
You can get more such selectors from here -> http://www.w3schools.com/css/css_attribute_selectors.asp
Basically, jQuery selectors are CSS selectors...

Categories

Resources