How to change class of an element from ng-repeat? - javascript

I'm getting info from a json file and creating a table with the results. what i need to do is to change the class of one of the elements on a click.
this is part of my code:
$scope.firstAvailables = function(){
$http.get('/app/json/products.json')
.then(function(data){
$scope.listOfProducts = data.data.products;
}
The html view:
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Nickname</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in listOfProducts">
<th><a class="one">{{x.name}}</th>
<th><input type="text" class="form" id="theBox" value="1" style="width:40%"></th>
<th><button type="button" class="btn btn-primary" ng-click="toChange(x)">Change</button></th>
</tr>
</tbody>
</table>
What i want to do is to change the class from the input on different rows (not all, just a few). For that, i'm using the next piece of code that lives inside of toChange(x) (which lives on the button):
$scope.toChange = function(val){
//to get the specific value
var specific = val;
//to create a new name for the class
var y = 'some-' + specific.name;
//with JQuery remove the previous class and add the new one
$('#theBox').removeClass('algo').addClass(y);
//With this i receive on the console all the input html tag
console.log(document.getElementById('theBox'));
}
To here everything it's ok if i click on one row. But, if then i click on another, the class from the selected row, sum the name previous name and the new instead of replace:
console log from very first clicked element
<input type="text" class="algo-non" id="theBox" value="1" style="width:40%">
console for the second element
<input type="text" class="algo-non algo-mollit" id="theBox" value="1" style="width:40%">
console for the next element
<input type="text" class="algo-non algo-mollit algo-liquit" id="theBox" value="1" style="width:40%">
What can i do to prevent the sum of the previous class names? The idea is to have on every click:
first click:
<input type="text" class="algo-non" id="theBox" value="1" style="width:40%">
second click:
<input type="text" class="algo-mollit" id="theBox" value="1" style="width:40%">
third click:
<input type="text" class="algo-liquit" id="theBox" value="1" style="width:40%">
I'm using AngularJs, Javascript and Jquery.
Thanx in advance.

The problem is that $('#theBox') is selecting all of the inputs.
First click: the class algo-non is added to all of the inputs.
Second click: the class algo-mollit is added to all of the inputs.
Third click: the class algo-liquit is added to all of the inputs.
Use id="theBox-{{ $index + 1 }}" or id="theBox-{{ item.name }}", then select the inputs individually.
// Guaranteed to be unique
<input type="text" class="form" id="theBox-{{ $index + 1 }}" value="1" style="width:40%">
// Risk duplicates (if items have same name)
<input type="text" class="form" id="theBox-{{ x.name }}" value="1" style="width:40%">

Related

How to change <td> value only in a specific row with jQuery?

If I have a table with 2 columns, a textfield and a checkbox... Each column has a class, and multiple rows in it. I don't know how to work this out:
If the textfield's number larger than 10, that row's checkbox automatically change from unchecked to checked.
Any ideas?
ok .. you can get the value of the input .. and in every keystroke check if the entered number is greater than 10 then loop through all the checkboxes and check them like that
$(".textfield").on("input", function () {
if (+$(this).val() > 10) {
$(".checkboxes").prop("checked", true)
} else {
$(".checkboxes").prop("checked", false)
}
})
you can try this and tell me if something went wrong
note : I added (+) before the $(this).val() to make sure the value is converted from string to number
edit: if you want to make an input for every row so this will not work!
you can make a specific class for every row and put the same class as a data attr in every input .. and then you can directly access to the input specific row checkboxes like that
$(".textfields").on("input", function () {
if (+$(this).val() > 10) {
$(`.${$(this).attr("data-id")} > td >
checkboxes`).prop("checked", true)
} else {
$(`.${$(this).attr("data-id")} > td >
checkboxes`).prop("checked", false)
}
})
I hope this works .. I know It's a little bit confusing .. by understanding the main idea you solve it with multible solutions
If you can't understand this let me know
$('.input').on('blur', function() {
if(parseInt($(this).val()) > 10){
$(this).parent().closest('tr').find('.checkbox').attr("checked","checked");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" class="input">
</td>
<td>
<input type="checkbox" class="checkbox">
</td>
</tr>
<tr>
<td>
<input type="text" class="input">
</td>
<td>
<input type="checkbox" class="checkbox">
</td>
</tr>
<tr>
<td>
<input type="text" class="input">
</td>
<td>
<input type="checkbox" class="checkbox">
</td>
</tr>
<tr>
<td>
<input type="text" class="input">
</td>
<td>
<input type="checkbox" class="checkbox">
</td>
</tr>
</table>
You need use blur of jQuery, it means when the user looses the focus from input/textfield then implement the functionality of checkbox to be checked, this is for single input and checkbox, if you want to achieve it for multiple row with column then see the above snippet.
$('#input_field').on('blur', function() {
if(parseInt($(this).val()) > 10){
$('#checkbox').attr("checked","checked");
}
});

Can't set checked attribute in radio button (radio button inside table)

I tried setting radio button checked to checked="checked" however this does not seem to work .
I have tried using
$(id_radio).prop('checked',true);
document.getElementById("id_radio").checked = true;
document.getElementById("id_radio").checked = true;
document.getElementById("id_radio").checked;
$(id_radio).attr('checked',checked);
But none of them seems to be changing the attribute of checked to checked="checked"
Below is my code
js_file.js
$(document).ready(function(){
$("document").on("click",".class_radio3",function(){
var id_radio=$(this).attr('value');
$(id_radio).prop('checked',true);
console.log(id_radio);
});
});
My code for creating table
<br>
<p class="uk-text-primary uk-text-bold"><u> General Message </u></p>
<table class="uk-table uk-border-rounded uk-grid-width-* uk-panel-box uk-text-justify" border="1">
<!--create top table -->
<tr> <!--tr defines a row --> <!-- define row 1 -->
<th class="uk-width-1-10"> Recipient </th> <!-- th defines a header cell-->
<th class="uk-width-1-3"> Message </th>
<th class="uk-width-1-10"> Action </th>
<th class="uk-width-1-10"> Default message </th>
</tr>
<!-- row 2 : display results onwards and creates dynamically -->
<!-- input fields at the bottom -->
<?php
include "../connect.php";
$get_data2admin = $db->query("SELECT ID,message,user FROM test_table_1 WHERE user='General'");
if( $get_data2admin->num_rows >0 ){ //if selected rows is more than zero
while($row_msg = $get_data2admin->fetch_assoc()){
$row_msg_id=$row_msg['ID']; //$row_msg['ID'] directly using it wont display in id tag attribute
echo "<tr>";
echo "<td>".$row_msg['user']."</td>";
echo "<td>".$row_msg['message']. "</td>";
?>
<td>Delete</td>
<?php
if($row_msg['user']=='General'){
echo "<td>"."<input class='class_radio3' type='radio' name='name_radio2' value='$row_msg_id' checked=''/>"."</td>";
}
else{
echo "<td>"."-"."</td>";
};
echo "</tr>";
}
}
?>
</table>
What could be the issue? Any insight/solution? Am a beginner in PhP any advice would be helpful. Thank you
Note
Its printing out the right id selected so i dont think its selection issue
A sidenote: another issue if i try using e.preventDefault at
$("document").on("click",".class_radio3",function(e){
e.preventDefault();
The radio button becomes un-clickable.Why is that so?
Update 1: Picture of what is the issue
Try This
HTML
if($row_msg['user']=='General'){
echo "<td>"."<input id='$row_msg_id' class='class_radio3' type='radio' name='name_radio2' value='$row_msg_id' />"."</td>";
}
JS
var id_radio=$(this).attr('id');
$('#' + id_radio).prop('checked',true);
Check the below,
You can use attr like below but i would recommend use prop
function chk(element) {
$(element).attr("checked", "checked");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="age">10</label>
<input type="radio" name="age" value="10" onclick="chk(this);" />
<label for="age">15</label>
<input type="radio" name="age" value="15" onclick="chk(this);" />
I think there are a couple of issues here... one is that only one radio can be checked per group - i.e. radios with the same "name". Having checked="" is the same as checked="checked" - the absence of the attribute altogether is the "unchecked" state.
div {
width: 50%;
float: left;
}
<div>
<h1>Group 1</h1>
<p><input type="radio" name="group1" value="1" checked="checked" />1</p>
<p><input type="radio" name="group1" value="2" checked="checked" />2</p>
<p><input type="radio" name="group1" value="3" checked="checked" />3</p>
<p><input type="radio" name="group1" value="4" checked="checked" />4</p>
<p><input type="radio" name="group1" value="5" checked="checked" />5</p>
</div>
<div>
<h1>Group 2</h1>
<p><input type="radio" name="group2" value="1" checked="checked" />1</p>
<p><input type="radio" name="group2" value="2" />2</p>
<p><input type="radio" name="group2" value="3" />3</p>
<p><input type="radio" name="group2" value="4" />4</p>
<p><input type="radio" name="group2" value="5" />5</p>
</div>
Secondly, in your code, you are saying (if I understand what PHP is outputting correctly), onclick of this input (radio), set the thing with an id that is the same as my value's property "checked" to true. That thing with an id is the a tag. An a tag does not have this checked property. See below where I'm setting its background to red (via a class), instead.
By default, a radio button will become checked on click, so you don't need to reiterate this default behavior.
I have also updated the code to respond when an input's value changes, as opposed to when the document is clicked and the target was the input. It is a little lighter performance-wise to listen for the more limited scope than the broader one you had. The approach that you used used to be referred to as a "live" listener in jQuery and is more appropriate for when JS is adding and removing elements that you're listening for on the page; in your case, PHP is rendering them, so we don't need it.
Additionally, jQuery selectors require a # to indicate id, a . to indicate class, and without these selectors, it assumes it is a tag. See below where I am appending a # to select the a with the id.
// This is listening for any radio buttons who were clicked, instead of any clicks on the document (it's a little more efficient)
$("input[type=radio]").on("change", function() {
// get the other radio buttons in this group
var $group = $('input[name=' + $(this).attr('name') + ']');
// Go through the group and if the input is checked, add the class to the corresponding element, otherwise, remove it
$group.each(function() {
var id_radio = "#" + $(this).attr('value');
if ($(this).is(":checked")) {
$(id_radio).addClass("radio-is-checked");
} else {
$(id_radio).removeClass("radio-is-checked");
}
});
});
.radio-is-checked {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="uk-text-primary uk-text-bold"><u> General Message </u>
</p>
<table class="uk-table uk-border-rounded uk-grid-width-* uk-panel-box uk-text-justify" border="1">
<!--create top table -->
<tr>
<!--tr defines a row -->
<!-- define row 1 -->
<th class="uk-width-1-10">Recipient</th>
<!-- th defines a header cell-->
<th class="uk-width-1-3">Message</th>
<th class="uk-width-1-10">Action</th>
<th class="uk-width-1-10">Default message</th>
</tr>
<!-- row 2 : display results onwards and creates dynamically -->
<!-- input fields at the bottom -->
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<!-- Since the radio in this row is checked by default, also apply the corresponding class -->
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='one' checked />
</td>
</tr>
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='two' />
</td>
</tr>
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='three' />
</td>
</tr>
</table>
Thirdly, the "default" behavior of a radio button is to become checked. By doing e.preventDefault you're cancelling that default behavior, so it doesn't become checked!

Get hidden fields from currently clicked td and first td of the current row

Consider a scenario
I have one table and having 8 columns, Each columns have some number of hidden fields - let's say 5 hidden fields.
What I'm trying to achieve is to get all the hidden fields' value when I click on particular cell and I also want hidden values from the first td of the currently clicked row from [cell]
Things achieved
I'm able to get the hidden field values of the currently clicked row cell's first child like following
element.closest("tr").find("td:first").find("input:hidden")
This will reult 3 as the first cell will always have 3 inputs.
Where I am stuck:
I'm getting the first cell's hidden inputs value but not able to get hidden inputs value of currently clicked cell.
Here is the sample HTML
<table>
<tr>
<td style="width: 50px;">4th Class( A )
<input id="SectionID" name="SectionID" type="hidden" value="7">
<input id="SectionDetailID" name="SectionDetailID" type="hidden" value="1">
<input id="SectionName" name="SectionName" type="hidden" value="4th Class( A ) ">
</td>
<td class="cells" onclick="fetchData(this);">
<div>
<div class="dataRow">
<div class="cellLabel">Name:</div>
<div class="cellValue">P D S</div>
</div>
<div class="dataRow">
<div class="cellLabel">Sub:</div>
<div class="cellValue">Hindi</div>
</div>
<div class="dataRow">
<div class="cellLabel">Period:</div>
<div class="cellValue">Period 2</div>
</div>
<div class="dataRow">
<div class="cellLabel">From:</div>
<div class="cellValue">11:00</div>
</div>
<div class="dataRow">
<div class="cellLabel">To:</div>
<div class="cellValue">12:00</div>
</div>
<div class="dataRow">
<div class="cellLabel">Year:</div>
<div class="cellValue">2014</div>
</div>
</div>
<input id="TimeTableDtlID" name="TimeTableDtlID" type="hidden" value="1">
<input id="TimeTableHdrID" name="TimeTableHdrID" type="hidden" value="7">
<input id="PeriodID" name="PeriodID" type="hidden" value="38">
<input id="PeriodName" name="PeriodName" type="hidden" value="Period 2">
<input id="PeriodFromTime" name="PeriodFromTime" type="hidden" value="11:00">
<input id="PeriodToTime" name="PeriodToTime" type="hidden" value="12:00">
<input id="TTYear" name="TTYear" type="hidden" value="2014">
<input id="SubjectName" name="SubjectName" type="hidden" value="Hindi">
</td>
<td class="cells" onclick="fetchData(this);">
<div>
<div class="dataRow">
<div class="cellLabel">Name:</div>
<div class="cellValue">J P Pl</div>
</div>
<div class="dataRow">
<div class="cellLabel">Sub:</div>
<div class="cellValue">English</div>
</div>
<div class="dataRow">
<div class="cellLabel">Period:</div>
<div class="cellValue">Period 2</div>
</div>
<div class="dataRow">
<div class="cellLabel">From:</div>
<div class="cellValue">11:00</div>
</div>
<div class="dataRow">
<div class="cellLabel">To:</div>
<div class="cellValue">12:00</div>
</div>
<div class="dataRow">
<div class="cellLabel">Year:</div>
<div class="cellValue">2014</div>
</div>
</div>
<input id="TimeTableDtlID" name="TimeTableDtlID" type="hidden" value="3">
<input id="TimeTableHdrID" name="TimeTableHdrID" type="hidden" value="7">
<input id="PeriodID" name="PeriodID" type="hidden" value="38">
<input id="PeriodName" name="PeriodName" type="hidden" value="Period 2">
<input id="PeriodFromTime" name="PeriodFromTime" type="hidden" value="11:00">
<input id="PeriodToTime" name="PeriodToTime" type="hidden" value="12:00">
<input id="TTYear" name="TTYear" type="hidden" value="2014">
<input id="SubjectName" name="SubjectName" type="hidden" value="English">
</td>
</tr>
</tbody>
</table>
jQuery
function fetchData(element) {
var $element = $(element);
var objHidden = [];
console.log($element.closest("tr").find('td:first').andSelf().find("input:hidden").length); // Returns 19 Where it must be 11
$element.closest("tr").find('td:first').andSelf().find("input:hidden").each(function (i, elem) {
objHidden[elem.getAttribute("name")] = elem.value;
});
console.log(objHidden); // Getting same values always
}
Fiddle DEMO
EDIT
It's Simple scenario when I click on cell means TD except the first one, I want hidden values from the currently clicked cells and also hidden values from the first TD in current row which is not clicked.
How to get hidden fields of currently clicked cell and hidden fields of the closest row's first td?
Any kind of help is greatly appreciated.
andSelf and the last jQuery object into the current stack. But if we look closely at your line :
$element.closest("tr").find('td:first').andSelf().find("input:hidden")
You do .closest().find().andSelf(). So that mean andSelf return the .closest('tr').
Try to use add instead :
$element.closest("tr").find('td:first').add($element).find("input:hidden")
Alternatively, you could use that as well :
$element.siblings(":first").andSelf().find("input:hidden");
From the jQuery documentation on andSelf():
When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .addBack() can help
So your query for:
$element.closest("tr").find('td:first').andSelf()
is actually returning not just the content of td:first, but also the content of the previous set of elements - which is the tr, not the element you originally clicked. Hence, you are getting all 19 hidden input elements, not just the 3 from the first cell and the 8 from the current.
[Edit - removed possible solution, the accepted answer is significantly neater than mine]
Not sure exactly what you are looking for so heres a quick demonstration of JQuery selectors running on your HTML to get certain parts.
http://jsfiddle.net/x3HN3/3/
(Click a cell and check log);
Please give some comment on what exactly you want from these fields..
$('table tr>td').click(function() {
var currentRow = $(this).parents('tr');
console.log(currentRow);
var currentCell = $(this);
console.log(currentCell);
var currentCellHtml = $(this);
console.log(currentCellHtml);
var numberOfHiddenCtrlsWithinCell = $(this).find(':input:hidden');
console.log(numberOfHiddenCtrlsWithinCell);
var numberOfHiddenCtrlsWithinRow = currentRow.find(':input:hidden');
console.log(numberOfHiddenCtrlsWithinRow);
});
From these variables you can get whatever you need using jquery selectors.. for example, to get the first table cell's html from the current clicked cell's row you'd do
currentRow.find('td:first').html();

Prepend text into each tag with specific ID

I have a tag system implemented into my website for three different categories. I set it up for a twitter account so I have "Keywords", "Mentions" and "Hashtags". What I need is that when a user inserts a tag in the text input for Mentions for it to prepend a "#" symbol before the text entered. The same goes for Hashtags except for the "#" symbol. I have put together a demo of what I have so far. Any help will be greatly appreciated.
JSFIDDLE
<div id="wrapper">
<table>
<tr>
<th></th>
<td id="keyword-filter">
<h5>Keywords</h5>
<input type="text" id="keywordInput">
<br>
Include:
<input type="radio" name="keywordInclude" checked="true">Any
<input type="radio" name="keywordInclude">All
<b>Keywords</b>
</td>
</tr>
<tr>
<th></th>
<td id="mention-filter">
<h5>Mentions</h5>
<input type="text" id="mentionInput">
<br>
Include:
<input type="radio" name="mentionInclude" checked="true">Any
<input type="radio" name="mentionInclude">All
<b>Mentions</b>
</td>
</tr>
<tr>
<th></th>
<td id="tag-filter">
<h5>Hashtags</h5>
<input type="text" id="hashtagInput">
<br>
Include:
<input type="radio" name="tagsInclude" checked="true">Any
<input type="radio" name="tagsInclude">All
<b>Hashtags</b>
</td>
</tr>
</table>
According to the documentation and source code of the tagsInput plugin you can use the onAddTag callback to fire whenever a tag is added. You can grab the tag element which is just created in the DOM and prepend the text with a #.
See the updated jsfiddle for a working example. You also need to check if the user didn't enter a # already.
$('#mentionInput').tagsInput({
'defaultText':'add name',
'onAddTag':function(tag) {
var span = $('#mentionInput_tagsinput .tag span').last();
if (span.text().substring(0, 1) != '#') {
span.text('#' + span.text());
}
}
});

Jquery .datepicker() - on a dynamic table

I am trying to create a dynamic table with each row containing two date fields. I am using Jquery datepicker. For some reason only the first row is showing in the date picker calendar. Other dynamically created fields are not showing the calendar. I should mention that the first row is by default in place when this page is loaded. Only from the second line it's dynamically created. All solutions say I should reinitialize the .datepicker(). I did and it's not working. I tried changing names and Ids still no solution. Is there something I am missing here. Below is the code used for this purpose.
Yes I know there are several questions related to this here in this site. But some how I couldn't find a solution to this as they aren't working for me.
Javascript:
$("#addurl").click(function(){
var idValue = "input[id='breachCount']";
var counter = $(idValue).val();
var trValue = $("#rowPH"+counter).html();
var countNew = parseInt(counter)+1;
$(idValue).val(countNew);
var newFile = "<tr id='rowPH"+countNew+"'>"+trValue+"</tr>";
$(newFile).insertBefore("#addLink");
var nameTemp, actNm;
var dcounter=0;
$('#rowPH'+countNew+' input').each(function(){
nameTemp = $(this).attr("name");
if(nameTemp){
actNm = nameTemp.substring(nameTemp.indexOf("."));
$(this).attr("name","breachList["+countNew+"]"+actNm+countNew);
}
});
$('.datepicker').each(function(i) {
this.id = 'datepicker' + i;
}).datepicker();
});
Html:
<table>.....
<tr id="rowPH0">
<td>
<input type="checkbox" checked="checked">
</td>
<td>
<input class="text_box_2 div_center" type="text" value="" name="breachList[0].breachText">
</td>
<td>
<input id="datepicker0" class="datepicker date_txt hasDatepicker" type="text" value="" name="breachList[0].activationDt"><img class="calendar" src="assets/images/calendar_icon.png">
</td>
<td>
<input id="datepicker1" class="datepicker date_txt hasDatepicker" type="text" value="" name="breachList[0].deactivationDt">
<input type="checkbox" name="breachList[0].deactiveNa" checked="checked">
</td>
<td>
<input class="text_box_2" type="text" value="" name="breachList[0].note">
</td>
</tr>
</tbody>
<tbody>
<tr id="rowPH1">
<td>
<input type="checkbox" checked="checked">
</td>
<td>
<input class="text_box_2 div_center" type="text" value="" name="breachList[1].breachText1">
</td>
<td>
<input id="datepicker2" class="datepicker date_txt hasDatepicker" type="text" value="" name="breachList[1].activationDt1">
<img class="calendar" src="assets/images/calendar_icon.png">
</td>
<td>
<input id="datepicker3" class="datepicker date_txt hasDatepicker" type="text" value="" name="breachList[1].deactivationDt1">
<input type="checkbox" name="breachList[1].deactiveNa1" checked="checked">
</td>
<td>
</tr>
<tr id="addLink">
<td colspan="5" >+ Add another row
<input type="hidden" id="breachCount" value="${fn:length(auditStandardBreachsForm.breachList)-1}"/>
</td></tr>
...</table>
Not necessary to assign unique ids to each field. Datepicker can identify each uniquely. Try putting following code in your js.
$('.datepicker').each(function(){
$(this).datepicker();
});
I've used it for multiple fields.
*Update*
I read your js code and it's messed up. All you want to do is (from what you've stated) is when user clicks on Add Another Link , you want to add a new row in table and want them to be able to work with jQuery datepicker. Right?
The reason above code is not working is, in this case, text fields are being added dynamically . While datepciker gets initialized on onDocumentReady. So datepicker can not attach itself to these newly created form fields. A solution is to attach datepicker while creating new fields itself.
Here's a working model I prepared for what you want to achieve. See demo on http://jsfiddle.net/phazorrise/bRE6q/
here is my updated code
Javascript
Modified at the bottom of the above javascript
var nameTemp, actNm;
$('#rowPH'+countNew+' input').each(function(){
nameTemp = $(this).attr("name");
if(nameTemp){
actNm = nameTemp.substring(nameTemp.indexOf("."));
$(this).attr("name","breachList["+countNew+"]"+actNm);
$(this).attr("id","breachList["+countNew+"]"+actNm+countNew); //added
}
});
$('.datepicker').each(function(i) {
$(this).removeClass('hasDatepicker').datepicker(); //changed ref: phazor comment
});

Categories

Resources