Unable to fetch value : JQUERY - javascript

I m creating dynamic rows with two td and text Host-Address is dynamically populated from GET request.
<tr>
<td class='hostId'>Host-Address</td>
<td>
<input id="btnProv" type='button' onClick="enablePro()" class='btn-success' value="Provision">
</td></tr>
I need to fetch that value using jquery
function enablePro(){
//var ipAddr = $(this).parent().siblings("td").first().text();
var row = $(this).closest('tr');
var ipAddr = row.find('td.hostId').text();
alert(ipAddr);
}
But i get a empty alert box Please enlight my mistake

You need to pass this to the function
onClick="enablePro(this)"
function enablePro(elem){
var row = $(elem).closest('tr');
this refers to the window object inside the function when you bind events inline.
Bind the event using javascript instead of inline events, then this points to the element that triggered the event.
$('.btn-success').click(enablePro);
Check Fiddle

You have to pass this or this.id to the function:
this refers to the object of that control while this.id will give you the id of control
onClick="enablePro(this.id)"
function enablePro("#"+sender){
var row = $(sender).closest('tr');
var ipAddr = row.find('td.hostId').text();
alert(ipAddr);
}

Related

Retrieve the name of a button created with innerHTML

I'm trying to retrieve the name of a button created using innerHtml. My problem is really simple to understand, and sure enough, to solve. Thanks in advance!
this is my code, adding a column to a dynamic table:
colonne1.innerHTML = '<td align="center"><input id=' +
button_id_is_id_plat+ ' type="button" name='+title+' value="Supprimer"
onclick="DeletePlat('+button_id_is_id_plat+')"></td>';
the name which contains the variable title, is what i'm looking to retrieve in my DeletePlat function. Here is what I've tried but with no positive results:
var my_array=document.getElementById("plat_action"); //the id of the dynamic table
var longueur = arrayLignes.length;
while(i<longueur)
{
//I retrieve the cell which contains a string
var cellule = my_array.rows[i].cells[0];
//I retrieve the cell which contains the button that I've created with innerHTML
var cellule2 = my_array.rows[i].cells[1];
//Here, I want to retrieve the name of the button embedded into my "cellule2" variable
if (cellule.innerText.toString()==cellule2.innerText.toString())
{
//treatment...
}
}
I've also tried cellule2.name.toString(), but, it seems that it ain't the solution too.
Here an example of what you could do in order to retrieve the name from a button html element:
let buttonElement = document.getElementById("button");
let name = buttonElement.getAttribute('name');
console.log(name)
<button name="buttonname" type="submit" value="HTML" id="button">HTML</button>
To rerieve the name of a button no need to call toString() function : just use the .name attribute of your DOM element :
console.log(document.getElementById("button").name);
<div id="div">
<button id="button" name="nameOfButton">Button</button>
</div>

Adding custom attribute values of dynamically created dropdowns to another element

I have a bit of HTML here:
<tr taskId="(#=obj.task.id#)" assigId="(#=obj.assig.id#)" class="assigEditRow" >
<td><select name="resourceId" class="get-resources formElements"></select></td>
<td><span class="resources-units"></span></td>
<td><span class="resources-quantity"></span></td>
<td><input type="text" placeholder="Required Q"></td>
<td align="center"><span class="teamworkIcon delAssig" style="cursor: pointer">d</span></td>
</tr>
And a bit of JS here:
'use strict';
function addResourceFunction(){
let ResourcesJSON = (json) => {
let Resources = json;
console.log(Resources);
let contactsLength = json.length;
let arrayCounter = -1;
let resID;
let resName;
let resUnit;
let resQuantity;
let Option = $('<option />');
let assignedID = $('tr.assigEditRow:last').attr("assigId");
while(arrayCounter <= contactsLength) {
arrayCounter++;
resID = Resources[arrayCounter].ID;
resName = Resources[arrayCounter].name;
resUnit = Resources[arrayCounter].unit;
resQuantity = Resources[arrayCounter].quantity;
$('.assigEditRow').last().find('select').append($('<option>', {
value: resName.toString(),
text: resName.toString(),
resourceID: resID.toString(),
resourceUnit: resUnit.toString(),
resourceQuantity: resQuantity.toString()
}));
}
}
$.getJSON("MY JSON URL IS HERE", function(json) {
ResourcesJSON(json);
});
};
So what's actually going on here: I get my data from the URL (JSON array), trigger the addResourceFunction() on click to create a new table row and to add a new select with options passed from the array. As you see from my HTML markup, the select input is placed in td.get-resources, and all that works good. I get my date set, I populate the select field and all works good. I can add as many rows/select dropdowns as I want.
Also, every option has a few custom attributes (you can see it in my JS code above), and I want to add the values of those attributes to the second and third column of the row (in HTML those are span.resources-units and span.resources-quantity). The thing is, I have no clue how to make it work 1:1, meaning that one select dropdown "alters" only units and quantity of its own row. Below is the code for that:
let idCounter = 1;
$(document).on('change', '.get-resources', function() {
$('.assigEditRow').last().find('.resources-units').attr('id', 'units-' + idCounter);
$('.assigEditRow').last().find('.resources-quantity').attr('id', 'quantity-' + idCounter);
this.resourceUn = $( ".get-resources option:selected" ).attr( "resourceUnit" );
this.resourceQuant = $( ".get-resources option:selected" ).attr( "resourceQuantity" );
$('#units-' + idCounter).append(this.resourceUn);
$('#quantity-' + idCounter).append(this.resourceQuant);
idCounter++;
});
What happens is that if I add one select input, and change options, the thing works. When I add another one and change its options, it gets attributes of the first one. Adding more - same thing. Whatever I change, it takes the attribute value of the first item added.
Try getting the id from the element instead of from the variable, since you always update the element with the id of the counter, instead of the element with the id of the row that was clicked.
Hmm, what does the counter do exactly? The more I look at it, the less I understand. What I do know is that you're not selecting the correct elements by using the idCounter to reference the correct row.
You want to do something like
$(document).on('change', '.get-resources', function() {
//var row = this;
this.find(/* Some path to the second column */).att(/* some att to change */);
this.find(/* Some path to the third column */).att(/* some att to change */);
});
where you always use the row as the root again, instead of finding a certain id, so you only update that row.
Native:
<table>
<tr>
<td>
<select>
<option data-text="resName1" data-resourceID="resID1" data-resourceUnit="resUnit1" data-resourceQuantity="resQuantity1">1</option>
<option data-text="resName2" data-resourceID="resID2" data-resourceUnit="resUnit2" data-resourceQuantity="resQuantity2">2</option>
<option data-text="resName3" data-resourceID="resID3" data-resourceUnit="resUnit3" data-resourceQuantity="resQuantity3">3</option>
</select>
</td>
<td>
<div class="column2"></div>
</td>
<td>
<div class="column3"></div>
</td>
</tr>
</table>
<script>
document.addEventListener('change', function ( event ) {
var select = event.target,
option = select.options[select.selectedIndex],
values = {
'text' : option.getAttribute('data-text'),
'resourceID' : option.getAttribute('data-resourceID'),
'resourceUnit' : option.getAttribute('data-resourceUnit'),
'resourceQuantity' : option.getAttribute('data-resourceQuantity')
},
row = select.parentNode.parentNode,/* depending on how deep the select is nested into the tr element */
column2 = row.querySelector('.column2'),
column3 = row.querySelector('.column3');
column2.textContent = 'some string with the values you want';
column3.textContent = 'some string with the other values you want';
});
</script>
Basically you start with the select that was changed, from there you get the option node that was clicked. Then you get the attributes you need from that option. Then you go up a few nodes to the row parent and find the two columns inside that row. Then you can set the content of these two columns.

.onchange or .onclick and checkbox value to JS script

I have an array of checkboxes group into class='year'. I would like to call a function in JS when a checkbox is checked.
The html is,
<table class="inner" id="searchTable">
<search>Exam Type:<th>
<?php
foreach($exams as $key=>$value):
echo "<tr><td class='left'><input type='checkbox' class='year' id='$key' name='$key' value='$value'
if ($category['selected'])
{
echo ' checked';
}
> $value</td></tr>";
endforeach; ?>
</table>
This table is inside a form. but I am too worried about the form at the moment.
The JS should create a table with a row when any checkbox is checked.
function yearTable(){
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
var empty = document.createTextNode("year.value");
/*var empty = document.createTextNode("");*/
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
document.getElementByClassName('year').onchange = yearTable;
I have tried using .onchange and .clicked but neither do anything when a box is checked.
Also I need the value checked in the JS.
I tried year.value but that doesn't work. Prviously I has a select options menu with id = 'exam' and I was able to get the value using exam.value but I can't figure out how to do soemthing equivalent for these checkboxes.
Any help would be greatly appreciated.
Thanks
While an html document may contain only one element with a specific id, there can be several elements with the same class.
So, there is no such a function as document.getElementByClassName. There is a function document.getElementsByClassName, and it returns an array of elements, so could call that function and then iterate over its return value, setting the needed callbacks.
Also, the code you posted must have thrown an exception at this line:
document.getElementByClassName('year')
So if you looked at developer tools in Chrome or Firebug in Firefox, you would probably see an error.
Got it,
function yearTable(){
var year = this.value;
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
if (this.checked){
var empty = document.createTextNode(year);
}
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
var checkboxes = document.getElementsByClassName('year');
for(var index in checkboxes){
checkboxes[index].onchange = yearTable;
}
Thanks

How do you pass html input text into a javascript function as a parameter?

My code is below. I would like the player to input their name into the html form and for this value to be submitted into the javascript scorecard class so that this.players = "name". How would I best do this? I have been trying to use jquery but am having no success.
HTML:
<section class="name1-2-12">
<form class='name' action=''>
<input type="text" name="name" placeholder="NAME">
<input type='submit' name='submit'>
</form>
</section>
JAVASCRIPT:
var Scorecard = function() {
this.players = 0;
};
Scorecard.prototype.addPlayer = function(name) {
this.players = name
};
The jQuery solution is nice, but a bit overdressed for the occasion.
Plain JavaScript:
You aren't really accustomed to JavaScript I guess:
var Scorecard = function() {
this.players = 0;
};
Scorecard.prototype.addPlayer = function(name) {
this.players = name
};
This code does two things:
It creates a constructor function called Scorecard. With this function you can create instances (simply put copies) of Scorecard.
You add a function to the Scorecard master object by using the prototype. Everything added via prototype will be shared by all instances of Scorecard
To sum this up. This isn't the way to go for the functionality you want. Consider this:
var Scorecard = function() {
this.players = 0;
this.playerList = []; //create a new Array() using shorthand [];
this.addPlayer = function(name)
{
this.players++; //add one to the player count.
this.playerList.push(name); //add a player to the playerlist using array.push().
}
};
What is this code doing:
It creates a master object called Scorecard.
A public variable is assigned called this.players. Public because it can be called upon outside the function Scorecard.
The same is done for the array: this.playerList.
A public method is added. Note this function only applies to the instance and is not shared with all instances.
The method addPlayer does two things. It takes name as argument. First it adds one to the public variable this.players by using ++, which means add one. Secondly it adds a player to the array list by using the method push. Which appends an item to an array.
Now we need to create a submit event. When the user submits the form, a player is added to the Scorecard.
var scorecard = new Scorecard(); //first create an instance of Scorecard
document.querySelector("form").addEventListener("submit", formAddPlayer, false);
function formAddPlayer(e)
{
e.preventDefault(); //e is the submit event. preventDefault stops it from actually posting the form, causing the page to reload.
var name = e.target.querySelector("input[name='name']").value //get the value from the input element.
scorecard.addPlayer(name);
//show the results
alert("Player amount: " + scorecard.players + "\nPlayers: \n -" + scorecard.playerList.join("\n -") ); //show the results
}
What is the code doing:
It creates a new instance (copy) of Scorecard named scorecard.
That instance has two properties: players and playerList and one method: addPlayer.
Attach an onsubmit event to the form. I used document.querySelector for this. Since your page only has one form, we can select the first form that the querySelector function comes across. We use addEventListener to attach the event. When the submit button is clicked the function formAddPlayer will fire. Note that formAddPlayer is passed as a reference not as a function call.
The actual formAddPlayer function: the argument e refers to the event. In this case a submit event. The actual submitting is cancelled using e.preventDefault(). The we use querySelector on the form element (retrieved using the target, which is the form, of the submit event). We select the input element with the name : name and retrieve it's value using value. We pass this value to the method addPlayer of the instance scorecard.
Al together:
function Scorecard() {
this.players = 0;
this.playerList = []; //create a new Array() using shorthand [];
this.addPlayer = function(name) {
this.players++; //add one to the player count.
this.playerList.push(name); //add a player to the playerlist using array.push().
}
};
var scorecard = new Scorecard(); //first create an instance of Scorecard
function formAddPlayer(e) {
e.preventDefault(); //e is the submit event. preventDefault stops it from actually posting the form, causing the page to reload.
var name = e.target.querySelector("input[name='name']").value //get the value from the input element.
scorecard.addPlayer(name);
//show the results
alert("Player amount: " + scorecard.players + "\nPlayers: \n -" + scorecard.playerList.join("\n -")); //show the results
}
document.querySelector("form").addEventListener("submit", formAddPlayer, false);
<section class="name1-2-12">
<form class='name' >
<input type="text" name="name" placeholder="NAME">
<input type='submit' name='submit'>
</form>
</section>
http://jsfiddle.net/55u2b81j/
With jQuery:
var aScorecard = new Scorecard();
$('form.name').on('submit',function(e){
e.preventDefault();
var name = $(this).children('input[name="name"]').val();
aScorecard.addPlayer(name);
});

editing dynamically generated table

I have a dynamically generated tables the foot of the table contain some text fields when click on save i want to add the value of text fields to the body of that table .
here is the table
<table border="1" class="entity_table">
<tfoot>
<tr>
<td>
<div class="pane1"></div>
<div class="pane2">
<input type="text" id="name"><br>
<select id="data">
<option value="1">int</option>
<option value="2">tinyint</option>
</select>
<br><span id="save">save</span>
</div>
</td>
</tr>
</tfoot>
<tbody class="table-body" id='myid'></tbody>
</table>
i did this but this is id specific ..i want to update that specific table on which it is clicked and edited .
var myName = document.getElementById("name");
var data = document.getElementById("data");
var Mtable = document.getElementById("myid");
var rowCount = Mtable.rows.length;
var mrow = Mtable.insertRow(rowCount);
var mcell = mrow.insertCell(0);
mcell.innerHTML = myName.value;
var mcell1 = mrow.insertCell(1);
mcell1.innerHTML = size.value;
i want to update each dynamically generated table with values that is entered in its table's foot section
You can use below jQuery :
$(function(){
$('#save').click(function(){
$(this).closest('table').find('tbody').append('<tr><td>'+$('#name').val()+' and '+$('#data').val()+'</td></tr>');
});
});
Demo
EDIT - to eliminate input and select box id dependency use below code :
$(function(){
$('#save').click(function(){
var name = $(this).closest('tr').find('input[type=text]').val();
var data = $(this).closest('tr').find('select').val();
$(this).closest('table').find('tbody').append('<tr><td>'+name+' and '+data+'</td></tr>');
});
});
Demo
So if I understood this right, you dont want to use element's ID to select it.
You have some else options if you dont want to work with elements IDs:
1) You can add them some data- attribute, for example: data-id. And based on this you select your element like this:
myElement.querySelector("[data-id='X']") where myElement is some parent element of your tables and X is their ID which you generated before (lets say it will start from 0 and will increment with every next table).
2) If possible, work with objects. When you create your tables, you either create them with raw text with defining html elements or you create new elements with calling createElement("table") on document keyword. If second option is your option, you can save this elements to some array (myTables in this case) and then approach this elements in a standard way - lets say:
myTables[0].getElementsByTagName("input")
Hope it helps your issue. Hope I understood issue you were asking about.

Categories