Get input value from each row in JavaScript - javascript

function shortDescription(a){
var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
}
This code works perfectly but how do I write this in pure JavaScript? I'm mainly interested in this: How do I perform these tasks without jQuery?
for each row, find the input name that ends in 6#if (the column I want)
on enter, get this input value and add to the console it so I know it's there
input id = "grid#21.125#1,6#if" type="text" value"" name="grid#21.125#1,6#if
oninput = shortDescription(this);

It would be great if you could share a piece of HTML on wich we could try some things, but for the moment, here's what your code looks like written in pure JS :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content')
Array.from(tbl.getElementsByTagName('tr')).forEach(function(tr) {
Array.from(tr.querySelectorAll("input[name$='6#if']")).forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
input.value = descriptionInput; // why ??
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = descriptionInput;
}
console.log(descriptionInput);
}
});
});
If you're not OK with the querySelectorAll, you can use getElementsByTagName, it returns a NodeList that you can turn into an array with the Array.from method and the use filter on the name to find the input with a name containing "6#if".
Best practices ...
Since an ID is unique and the methods getElementsByTageName or getElementsByTagName returns a Live HTMLCollection, it's better if you use these elements as unique variables, so you won't ask your browser to fetch them many times.
Since I don't know what your elements means, I will name the variables with trivial names, here's a better version of the code :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content');
var tr1 = tbl.getElementsByTagName('tr');
var el1 = document.getElementById('__AGIM0:U:1:4:2:1:1::0:14');
var inputsInTr = Array.from(tr1).map(function(tr) {
return Array.from(tr.getElementsByTagName('input'));
}).reduce(function(pv, cv) {
return pv.concat(cv);
});
var myInputs = inputsInTr.filter(function(input) {
return input.name.indexOf('6#if') != 0;
});
myInputs.forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
el1.value = descriptionInput;
}
console.log(descriptionInput);
}
});
I didn't try it, hope it's OK.
Hope it helps,
Best regards,

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

Javascript HTML Table Search

I have this code to search data in my tables. I'm trying to add a class on the found rows. It works, however once the search input field is empty, it still keeps the class on the cells. Is there any quick way to remove the class once the search field is empty/found is false?
$(document).ready(function() {
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal) {
var table = $('.phonetable');
table.find('tr').each(function(index, row) {
var allCells = $(row).find('td');
if(allCells.length > 0) {
var found = false;
allCells.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text())) {
found = true;
return false;
}
});
if(found == true) $(row).show() .addClass("searchhighlight");
else $(row).hide();
}
});
}
Check if the value is empty and if it is remove the value:
$('#search').keyup(function() {
var value = $(this).val();
if(value)
searchTable();
else
$('.phonetable tr td').removeClass("searchhighlight");
});
Also look how I traverse the table with $('.phonetable tr td'), you can do something similiar in your current code.

onclick clone shipping address fields values to billing address fields values

Hi i have this javascript code
copyAddress : function(swapMode, container){
var thisInstance = this;
var addressMapping = this.addressFieldsMappingInModule;
if(swapMode == "false"){
for(var key in addressMapping) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+addressMapping[key]+'"]');
toElement.val(fromElement.val());
}
} else if(swapMode){
var swappedArray = thisInstance.swapObject(addressMapping);
for(var key in swappedArray) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+swappedArray[key]+'"]');
toElement.val(fromElement.val());
}
this code working fine if elements are input text fields
but not for select dropdown elements
I my form I have only input text and select fields and i want to modyfy this code to work with select fields too
I made a change to code like this
if(!(fromElement).is("select")) {
toElement.val(fromElement.val());
}else{
var $options = $(fromElement+" > option").clone();
toElement.append($options);
}
but without success.
Maybe anyone can help me please?
Thanks!
This will do your work.
I have added a check that if the element to copy is Select or not. In case of select element all the options of From element will be copied and appended to To element.
Try it and let me in case of any issue.
copyAddress : function(swapMode, container){
var thisInstance = this;
var addressMapping = this.addressFieldsMappingInModule;
if(swapMode == "false"){
for(var key in addressMapping) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+addressMapping[key]+'"]');
if(fromElement[0].tagName == "Select")
{
toElement.find('option').remove();
toElement.append(fromElement.find('option'));
}
toElement.val(fromElement.val());
}
} else if(swapMode){
var swappedArray = thisInstance.swapObject(addressMapping);
for(var key in swappedArray) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+swappedArray[key]+'"]');
if(fromElement[0].tagName == "Select")
{
toElement.find('option').remove();
toElement.append(fromElement.find('option'));
}
toElement.val(fromElement.val());
}
The solution was toElement.val(fromElement.val()).trigger("liszt:updated"); this work for all elements in form that use chosen.js

get index of input element in javascript

If I have 3 input boxes on a web page and the user clicks the second input, I need to get the input index, the position of the input on the page. I need it in pure javascript. This is what I have so far but it doesn't work...
document.querySelector('html').onclick = function (e) {
log(e);
}
function log(obj) {
var nodeName = obj.target.nodeName
var idx = nodeName.length
console.log(nodeName, idx);
}
Any help would be appreciated!
Pure javascript:
function getIndexFromSet(set, elm){
var setArr = [].slice.call(set);
for( var i in setArr )
if( setArr[i] == elm )
return i;
}
The above function can be used like so:
function checkInputFocus(e){
if(e.target && e.target.nodeName == 'input' )
index = getIndexFromSet(inputs, e.target);
}
var inputs = document.querySelectorAll('input');
document.addEventListener("click", checkInputFocus);
using jQuery, if you run this on this page (in your console)
var inputs = $('input'); // get all input elements on the page
inputs.index( $('#save-pinned-sites-btn') ); // find the index of spesific one
you will get a number representing the index of an $('#save-pinned-sites-btn') element
Inline:
<input onclick="for(i=0;i<this.parentNode.getElementsByTagName('input').length;i++){if(this==this.parentNode.getElementsByTagName('input')[i]){alert(i);}}">
Or change that to
onclick="show_index(this)"
And Add:
function show_index(which) {
for(i=0;i<which.parentNode.getElementsByTagName('input').length;i++){
if(which==which.parentNode.getElementsByTagName('input')[i]){
alert(i);
}}

How to match children innerText with user input using jQuery

I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});

Categories