Prevent Duplicate Append data in JavaScript and Html - javascript

I have one HTML table and I don't want the value of second column to repeat in the grid.
Here is my JavaScript:
var $addedProductCodes = [];
function getProductData(value){
$td_productCode=$("#sales-product-code").val();
var index = $.inArray($td_productCode, $addedProductCodes);
if (index >= 0) {
alert("You already added this Product");
} else {
$('#test').append("<tr><td>"+ value +"</td></tr>");
$addedProductCodes.push($td_productCode);
}
}
and Html
<tbody id="test">
<tr>
<td><input type="text" id="sales-product-code" name="cm_code[]" value="" class="sales-product-code"/> </td>
</tr>
</tbody>
Please help me out. Help is highly appreciated.

The call to
$('#test').append("<tr><td>"+ value +"</td></tr>")
should be replaced with
$('#test tr:last').after("<tr><td>" + value + "</td></tr>").
I created a JSFiddle example.

Try to use a boolean variable and use it in your conditional if. If the column is added, change the value for that variable.

Related

How to get the value of an input field inside the table td using javascript selector?

I have this line of code where it gets the value inside the td part of the table.
document.getElementById("supplierID").value = $tr.find('td:eq(0)').html();
The above code successfully get the data inside the td part of the table. E.g
<td>{{ $val->fname }}</td>
However, if the td has input field inside it
<td><input type='checkbox'style='width:30px; height:20px;' class='radio_check_all prod-id-checkbox' id='prod-id-checkbox' value="{{ $val->id }}"></td>
it returns the markup code of an input field using the code shown above. It doesn't get the right value. How would I do it? Please help. Thanks.
The following code snippet should work
check this
$(function(){
var table=$("table");
alert(table.find('tr td:eq(0) input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type='checkbox' style='width:30px; height:20px;' class='radio_check_all prod-id-checkbox' id='prod-id-checkbox' value="{{ $val->id }}"></td>
</tr>
</table>
Hope this helps
So what you are saying is, if the element inside the table cell is an input, return the value. Otherwise if it is just text, return the text.
var $el = $('tr td:eq(0)'),
testEl = $el.has('input').length;
document.getElementById("supplierID").value = testEl ? $('input', $el).val() : $el.text();

Cloning a table row

I have the following table
<table id="customFields" class="table table-bordered table-hover additionalMargin alignment">
<thead>
<tr>
<th colspan="2"></th>
<th>Some Title</th>
</tr>
</thead>
<tbody>
<tr>
<td><label class="subjectline" for="User1">User NOC M1</label></td>
<td id="slLabel">SLA</td>
<td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
<td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
</tr>
</tbody>
</table>
I then have the following javascript to add additional rows
$(function() {
$(".addCF").click(function(){
$("#customFields").append('<tr><td></td><td>SL_B</td> <td><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td> <td> Remove</td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
This currently works how I want it to. However, there are a couple of things I am having issues with.
Firstly, when you first view it, you will see the label SL_A. In the cloned version, I manually set it to SL_B. All other clones then have SL_B. What I am trying to do is have SL_ followed by the next letter in the alphabet. So the third row should be SL_C. I am not too sure how I can achieve this.
My second issue relates to the name of the cloned input. At the moment, they all have the same name e.g. slOptions[User][NOC M1]
When a new row is added, the name should change to something unique, maybe using the additional letter of the alphabet above e.g. slOptions[User][NOC M1B]
Would it be possible to achieve these things?
I have set up a Fiddle for demonstration
Thanks
You could store a reference to the possible letters as well as your current letter and then within your function determine the appropriate one to use :
// Store the possible letters
var possibleLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Store the current letter
var currentLetter = 'A';
$(function() {
$(".addCF").click(function(){
// Resolve the next letter to add
var nextIndex = possibleLetters.indexOf(currentLetter) + 1;
// Update your reference
currentLetter = possibleLetters[nextIndex];
// Append it
$("#customFields").append('<tr><td></td><td>SL_' + currentLetter + '</td> <td><input type="text" name="slOptions[User][NOC M1' + currentLetter + ']"...');
// More code omitted for brevity
});
// Still more code omitted for brevity
});
You can see an example of this in action here and demonstrated below :
Here is your solution for both the issues:
See: https://jsfiddle.net/pdxgrpqz/
$(function() {
alp = "A";
$(".addCF").click(function(){
alp = (alp.substring(0,alp.length-1)+String.fromCharCode(alp.charCodeAt(alp.length-1)+1));
$("#customFields").append('<tr><td></td><td>SL_'+alp+'</td> <td><input type="text" name="slOptions[User][NOC M1'+alp+']" class="form-control" id="User1"></td> <td> Remove</td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});

How to loop through group of check boxes that have same class name?

I have dynamic table that has table cell with checkbox field. This fields are populated from DB so my table is dynamic. I would like to loop through checkboxes based on their class name. In that loop I want to check value for each check box. For example if value is equal 1 I want checkbox to be checked, if not unchecked. Alo I'm not sure if possible but I would like to set unique ID for each of these check boxes. Since my table is dynamic my fields need to have unique ID's. Here is example of my code:
<table>
<thead>
<tr>
<th>#</th>
<th>Time Slots</th>
<th>Block</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>~(SLOT_LABEL)</td>
<td>
<span>
<input type="checkbox" name="CF-[Events]" class="block" id="block_"+Value that will make this ID unique. value="~(SLOT_ID)"/>
</span>
</td>
</tr>
</tbody>
</table>
Also in current language that I work with to read values from DB I have to use NAME tag. If anyone can help please let me know. Thank you.
You can use the attribute selector to retrieve elements by both their name and value. Try this:
$('input[name="CF-[Events]"][value="1"]').prop("checked", true);
Working example
If you don't want a jQuery solution, it is also possible to fetch these elements with the querySelector:
var inputs = document.querySelectorAll("input.block");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
you can do it in jquery by each loop
$('.ClassName').each(function(i, o) {
// o is object in your case checkbox
// i is index
// your code
});
$("input[name='CF-[Events]']").each(function() {
if($(this).val() === "1")
{
$(this).prop("checked", true);
}
});

Get elements from Parent Row of checked checkboxes

I have the following row in a table.
<tr class="data_rows" ng-repeat='d in t2'>
<td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td>
<td class="tds"><a href='perf?id={{d.ID}}'>{{d.ID}}</a></td>
<td class="tds">{{d.HostOS}}</td>
<td class="tds">{{d.BuildID}}</td>
<td class="tds">{{d.Description}}</td>
<td class="tds">{{d.User}}</td>
<td class="tds">{{d.StartTime}}</td>
<td class="tds">{{d.UniqueMeasure}}</td>
<td class="tds">{{d.TotalMeasure}}</td>
</tr>
Here's the HTML for button that will invoke the function to collect the ids from checked check boxes and store them.
<div id='compButtonDiv' align='center' style="display: none;">
<input id='cButton' type='button' value='compare selections' onclick='submitSelection()' style= "margin :0 auto" disabled>
</div>
The data is in t2 which consists of an array of length 15-20.
What i want to do is get the value of ID i.e, {{d.ID}} of the 2 checked check boxes so that i can store them in a variable and pass them as query parameters to URL using `location.href = url?param1&param2'
Here's the javascript:
function keepCount(obj){
debugger;
//var count=0;
if(obj.checked){
obj.classList.add("checked");
}else{
obj.classList.remove("checked");
}
var count = document.getElementsByClassName("checked").length;
var cBtn = document.getElementById('cButton');
//alert(count);
if(count == 2){
cBtn.disabled = false;
}
else if(count < 2){
cBtn.disabled= true;
}
else{
cBtn.disabled= true;
alert("Please Select two sets for comparison. You have selected: " + count);
}
}
function submitSelection(){
// what should be the code here??
location.href= "existingURL?a&b";
}
Now can someone please tell me how to get the id's?? I need to extract ID from the checkboxes that are checked(on the click of button whose code i've mentioned above'.
Thanks.
-Ely
Firstly when we use angularjs we tend to depend less and less on DOM manipulation.
For this reason, what you can do is to attach ngModel to the checkbox.
Like:
<input class='checkBoxInput' ng-model='d.isChecked' type='checkbox' onchange='keepCount(this)'>
What this does is, it attaches the variable (in your case the property of item in the list) to the check box. If it is checked it is true, if unchecked, initially it will be undefined, later on checking and then unchecking it will be false.
Now, when you submit, just loop over the original list in the function and check the values of d.isChecked (true/falsy values). Then you can add the necessary items in a separate list for submission.
The only concern is when checking the list on submission , check if(d.isChecked), so that it ignores the falsy values(false/undefined).

Loop through form input fields with Javascript

Please help me out on this. I have Javascript like the following:
function calc() {
var table = document.getElementById(tableNum);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum[i] = document.formNum.txt1[i].value * document.formNum.txt2[i].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}
And HTML like this:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[]" onkeyup="calc()"/></td>
<td><span id="totalCalc[]"></span></td>
</tr>
</form>
</table>
The number of input fields is unknown. No error, but totalCalc field is empty. Please tell me what I have done wrong. Thanks.
EDIT: I'm sorry, I forgot to mention both the input fields are in a table. Please check the edited code. Thanks.
EDIT: I'm actually working on a demo which the number of table row is defined by user, by clicking insert row button.
EDIT: Thanks Travis for the code. After a few changes, the code is working now. But only the first row is working. I'm thinking to get the length of the row and to use for loop for the text fields. <input type="text" name="txt1[<?php echo $rowLength;?>]" onkeyup="calc()"/> Does anyone have other ideas? Thanks.
The first thing seems wrong is
document.getElementById(tableNum);
should be
document.getElementById("tableNum");
Secondly,
var totalNum[i] =
should be
var totalNum =
Also, its not working, you can find it out quickly by debugging through firebug or chrome's integrated developer tool. Which will help you for syntax verification as well.
Here is what is going on.
HTML first
If you are going to reference these by indices, then use proper indices, like this
name="txt1[0]"
name="txt2[0]"
<span id="totalCalc[0]">
Javascript
document.getElementById(tableNum);
getElementsById expects a string, so this should be
document.getElementById("tableNum");
Since you are iterating, you only need one of these variables since it is immediately used (not a whole array):
var totalNum = instead of var totalNum[i]
When you access the form using dot notation, the brackets in the name messes that up, you need to do it like this:
document.formNum["txt1["+i+"]"].value instead of document.formNum.txt1[i].value
Vuala
When you make these minor changes, the code you used will actually produce proper results :) See this working demo: http://jsfiddle.net/69Kj7/ , also, here is a demo with 2 rows: http://jsfiddle.net/69Kj7/1/
For reference, this is the code in the demo:
html:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[0]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[0]" onkeyup="calc()"/></td>
<td><span id="totalCalc[0]"></span></td>
</tr>
</form>
</table>​
js:
function calc() {
var table = document.getElementById("tableNum");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum = document.formNum["txt1["+i+"]"].value * document.formNum["txt2["+i+"]"].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}​
if you wants to work with pure java script and here is the logical code
html
<form name="formNum" id="formNum" action="" >
<input type="text" name="foo[]" onkeyup="calc()" value="5"/>
<input type="text" name="foo[]" onkeyup="calc()" value="12"/>
<span id="totalCalc"></span>
</form>
​
js
var inputs = formNum["foo[]"];
var total = 1;
alert(inputs.length);
for (var i = 0; i < inputs.length; i++) {
total *= inputs[i].value;
}
alert(total);
working DEMO
I've figured out how to solve the problem. Just insert array after totalCalc, but not within totalCalc.
Thank you guys so much for helping me out :)

Categories