I want to be able to add jquery UI to the list on GoalNotes This table gets populated by what the user enters in the "name1" and "data1" input fields. Every time I give the an id, the program breaks and I get no errors. Any ideas on how I could apply animations to the table rows that get added after the user inputs data?
html
<section class="section section--active color1" data-letter="M">
<article class="section__wrapper">
<h1 class="section__title">Monday</h1>
<div id="Monday" class="tabcontent">
<form name="goalsList1" action = "/created" method="POST">
<div id="tab1">
<table>
<tr>
<td><b>New Goal:</b><input type="text" name="name1" id="name1"></td>
<td><b>Notes:</b><input type="text" name="data1" id="data1"></td>
<td>
<input type="submit" value="Save" onclick="SaveItem(1)">
</td>
</tr>
</table>
</div>
<div id="items_table1">
<h2>List of goals</h2>
<table id="list1" contenteditable> </table>
<p>
<label><input type="button" value="Clear" onclick="ClearAll(1)"></label>
</p>
</div>
</form>
</div>
</article>
</section>
javascript
function doShowAll(numOfWeek) {
if (CheckBrowser()) {
var key = "";
var list = "**<tr><th>Goal</th><th>Notes</th></tr>**\n";
var i = 0;
var goals = localStorage[numOfWeek] ? JSON.parse(localStorage[numOfWeek]) : {};
var goalsKeys = Object.keys(goals);
for (i = 0; i < goalsKeys.length; i++) {
key = goalsKeys[i];
list += "<tr><td>" + key + "</td>\n<td>"
+ goals[key] + "</td></tr>\n";
}
if (list == "<tr><th>Goal</th><th>Notes</th></tr>\n") {
list += "<tr><td><i>nothin' here</i></td>\n<td><i>nothin' here either</i></td></tr>\n";
}
document.getElementById('list'+numOfWeek).innerHTML = list;
} else {
alert('Cannot store list as your browser do not support local storage');
}
}
$(document).ready(function(e) {
$('#due-date').datepicker();
$('#add-todo').button({
icons: {
primary: "ui-icon-circle-plus"
}
}).click(function() {
$('#new-todo').dialog('open');
}); // end click
$('#new-todo').dialog({
modal: true,
autoOpen: false,
close: function() {
$('#new-todo input').val(''); /*clear fields*/
},
buttons : {
"Add task" : function() {
var taskName = $('#task').val();
var dueDate = $('#due-date').val();
var beginLi = '<li><span class="done">%</span><span class="delete">x</span>';
var taskLi = '<span class="task">' + taskName + '</span>';
var dateLi = '<span class="due-date">' + dueDate + '</span>';
var endLi = '</li>';
$('#todo-list').prepend(beginLi + taskLi + dateLi + endLi);
$('#todo-list').hide().slideDown(250).find('li:first')
.animate({
'background-color': '#ff99c2'
},250)
.animate({
'background-color': '#d9b3ff'
},250).animate; // end animate
$(this).dialog('close');
},
"Cancel" : function() {
$(this).dialog('close');
}
}
});
$('#todo-list').on('click','.done',function(e) {
var $taskItem = $(this).parent("li");
var $copy = $taskItem.clone();
$('#completed-list').prepend($copy);
$copy.hide().slideDown();
$taskItem.remove();
}
); // end on
$('#todo-list, #completed-list').on('click','.delete',function(e) {
$(this).parent("li").slideUp(250, function() {
$(this).remove();
}); // end slideup
}); // end on
$('#todo-list').sortable();
}); // end ready
http://jsbin.com/digefufeca/edit?html,css,js,console,output
The problem
The form with nane goalsList1 is sending whenever you click on the button.
Why? because the button is submit button.
The solution(s)
Replace the button's type to button. (link)
Prevent the form submission by event.preventDefault(). (link)
There are more ways but those are the major.
Note: your code still not working but now you can see the error message.
Related
I am dynamically generating checkboxes from my database using jquery ajax to call my web api. The problem is that I am trying to get the length of the checkbox array but constantly receiving an array length of zero when i debug. Please what might be wrong with my code.
HTML CODE
<div class="panel-body">
<form method="post">
<div class="form-group">
<label>Add Role Name</label>
<input type="text" class="form-control" placeholder="Role Name" />
</div>
<div class="col-md-6">
<div class="well">
<fieldset id="appName">
</fieldset>
</div>
<input id="saveUrl" type="button" value="Add Role" class="btn btn-success pull-right" />
</div>
</form>
</div>
JQUERY CODE
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
method: 'GET',
url: 'http://localhost:61768/api/users/GetUrls',
headers: {
'Authorization': 'Basic ' + btoa(localStorage.getItem('ApplicationId') + ":" + localStorage.getItem('ApiKey'))
},
success: function (data) {
if (Object.keys(data).length == 0) {
alert("Ewoo");
} else {
$.each(data, function (index, value) {
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
$('#appName').append(input); //Where I generate the checkboxes
});
}
},
error: function () {
alert("DonDy");
}
});
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
$('#saveUrl').click(function () {
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
});
</script>
The result of click the save button is alerting bad
In this code checkbox is getting appended but you are not checking the checkbox
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
Here you are checking length of checked checkbox..hence alerting to bad :
var $checkboxes = $('input[name="chk[]"]:checked');
Try this and that to inside save url click fucntion:
$('#saveUrl').click(function () {
var $checkboxes = $('input[name="chk[]"]');
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
Since you are populating/creating checkbox inside an AJAX call, you should have $checkboxes inside the #saveUrl function, because before that, it would be empty when the JS is loaded. You need this variable when the #saveUrl is clicked, hence it should check for the checked inputs when the #saveUrl is triggered:
$('#saveUrl').click(function() {
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
I have a table that when I hit save, it would get all the input fields in the first column and check in the database if the data already exists. If the condition is true, it would show an icon per row. And when I click that icon, the info relevant to that specific data will show as a bootstrap modal.
I've been working on my problem the whole day. I first tried to make it work with only one data. When I got what I wanted, I started to work on multiple data.
When multiple data is checked and they are duplicates, only the last info is shown even if there are 2 or more.
Here's my code:
The save button:
$( "#save_Boxes" ).click(function() {
$.ajax({
type: "POST",
url: window.base_url+'oss/admin/check_receive_data',
data: $.param($('form#receiving-form').serializeArray()),
dataType : 'JSON',
success: function (response) {
var new_arr = response.receive_array;
console.log(new_arr);
var no_duplicate = 0;
//THIS IS WHERE THE PROCESS SHOULD TAKE PLACE
$('table#receiving-box-table tbody tr').each(function(index){
var ctno = $(this).find('td:first input').val(); // get courier trancking
var td_id = $(this).find('td:last button.duplicate-data').attr('id');
var target = $(this).find('td:last button.duplicate-data').attr('data-target');
// check if ctno is present in response array or not
var arr = $.grep(response.receive_array, function( n ) {
return ( n.courier_tracking_no === ctno);
});
if(arr.length){ // if present then show error message
// alert('wsdds');
no_duplicate = 1;
$(this).find('td:first input').attr('disabled', 'disabled');
$('button#'+td_id).show(); // let it be hidden by default
$(this).find('td:first input').closest('td').addClass('has-error');
}
var new_ctno = $('button#'+td_id).closest('tr').find('td:first input').val();
$.each(new_arr, function(idx, obj){
console.log(idx + ": " + obj.courier_tracking_no);
console.log(target);
$(target).on('hidden.bs.modal', function(){
$(target+' .modal-title').html('');
$(target+' .modal-body').html('');
});
$('button#'+td_id).off('click').on('click', function(){
$(target).load(window.base_url+'oss/admin/box_duplicate',
function(){
$(target+' .modal-title').html('Duplicate Courier Tracking Number - '+obj.courier_tracking_no);
$(target+' .modal-body').html("<p class='text-left'>This box already exists. Please delete.</p><table class='table table-hover table-bordered table-striped'><tbody><tr><th scope='row'>Batch No.</th><td>"+obj.batch_no+"</td></tr><tr><th scope='row'>Courier Name</th><td>"+ucword(obj.courier_name)+"</td></tr><tr><th scope='row'>Vendor Name</th><td>"+ucword(obj.vendor_name)+"</td></tr><tr><th scope='row'>Status</th><td>"+ucword(obj.status)+"</td></tr></tbody></table>");
$(target).modal('show');
});
});
});
});
if(no_duplicate == 0){
var check_if_empty = 0;
$('input[name^="courier_tracking_no[]"]').each(function(){
if($(this).val() != ""){
check_if_empty += 1;
}
});
if(check_if_empty > 0){
$('#receiving-form').submit();
}
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
console.log("There was an error: " + errorThrown);
}
});
});
The html table:
<table id="receiving-box-table" class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>Courier Tracking #</th>
<th>Courier</th>
<th>Vendor</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" form="receiving-form" class="form-control input-sm track_no" name="courier_tracking_no[]" id="courier_tracking_no_1" /></td>
<td><input type="text" form="receiving-form" class="form-control input-sm" name="courier_name[]" id="courier_name_1" onkeypress="if (event.keyCode == 13) {return false;}"/></td>
<td><input type="text" form="receiving-form" class="form-control input-sm" name="vendor_name[]" id="vendor_name_1" onkeypress="if (event.keyCode == 13) {return false;}"/></td>
<td class="box-action"><button class="btn btn-danger btn-xs clear-data" data-toggle="tooltip" data-placement="right" title="Clear input fields"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> <button style="display:none;" id="dup-0" data-toggle = "modal" data-target = "#dupli-modal-0" class="btn btn-warning btn-xs duplicate-data" title="Duplicate Data"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span></button><div class = "modal fade" id = "dupli-modal-0" tabindex = "-1" role = "dialog" aria-labelledby = "dupli-modal-0Label" aria-hidden = "true"></div></td>
</tr>
</tbody>
</table>
Note: Only the first row is shown because the following rows are dynamically created.
The html modal:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<div class="row" style="margin-left: 0; margin-right: 0;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>
</div>
</div>
What am I missing? Even if the modal comes from only 1 file, it has unique ID's so it should not be a problem.
Thanks for your help!
-Eli
I tried a different approach. Instead of calling a url (I use CI) and showing the file that holds the modal template, I directly added the template inside my code:
$( "#save_Boxes" ).click(function() {
$.ajax({
type: "POST",
url: window.base_url+'oss/admin/check_receive_data',
data: $.param($('form#receiving-form').serializeArray()),
dataType : 'JSON',
success: function (response) {
var new_arr = response.receive_array;
console.log(new_arr);
var no_duplicate = 0;
//THIS IS WHERE THE PROCESS SHOULD TAKE PLACE
var stored = [];
$('table#receiving-box-table tbody tr').each(function(index){
var ctno = $(this).find('td:first input').val(); // get courier trancking
var td_id = $(this).find('td:last button.duplicate-data').attr('id');
var target = $(this).find('td:last button.duplicate-data').attr('data-mod_id');
stored.push(target);
var arr = $.grep(response.receive_array, function( n ) {
return ( n.courier_tracking_no === ctno);
});
if(arr.length){ // if present then show error message
// alert('wsdds');
no_duplicate = 1;
$(this).find('td:first input').attr('readonly', 'readonly');
$('button#'+td_id).show(); // let it be hidden by default
$(this).find('td:first input').closest('td').addClass('has-error');
}
});
$('div.modal_holder').html('');
all_modals = '';
var modal_list = $.each(new_arr, function(idx, obj){
all_modals += "<div class = 'modal fade' id = '"+stored[idx]+"' tabindex = '-1' role = 'dialog' aria-labelledby = '"+stored[idx]+"Label' aria-hidden = 'true'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><button type='button' class='close' data-dismiss='modal'>×</button><h4 class='modal-title'></h4></div><div class='modal-body'><div class='row' style='margin-left: 0; margin-right: 0;'><p class='text-left'>This box already exists. Please delete.</p><table class='table table-hover table-bordered table-striped'><tbody><tr><th scope='row'>Batch No.</th><td>"+obj.batch_no+"</td></tr><tr><th scope='row'>Courier Name</th><td>"+obj.courier_name+"</td></tr><tr><th scope='row'>Vendor Name</th><td>"+obj.vendor_name+"</td></tr><tr><th scope='row'>Status</th><td>"+obj.status+"</td></tr></tbody></table></div></div><div class='modal-footer'><button type='button' class='btn btn-default' data-dismiss='modal'>Ok</button></div></div></div></div>";
});
$('div.modal_holder').html(all_modals);
console.log(no_duplicate);
if(no_duplicate == 0){
var check_if_empty = 0;
$('input[name^="courier_tracking_no[]"]').each(function(){
if($(this).val() != ""){
check_if_empty += 1;
}
});
console.log(check_if_empty);
if(check_if_empty > 0){
$('#receiving-form').submit();
}
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
console.log("There was an error: " + errorThrown);
}
});
});
I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>
I have a text box and a button. On the button . click function the name appears but I want id (that the user enters into the text box for the corresponding name to appear)
this is a snip from the json:
{"user":[{"ID" : "001","name": "Zara Ali"}]}
This is the button/text ( that i have inside an alert div because i think it looks cool in my page and works with the .click)
<div class="alert alert-info">
<input type="text" id="userName" value>
<button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button>
</div>
and this is the js i have used for the .click
$(document).ready(function() {
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
$('#details').html('<p> Name: ' + jd.name + '</p>');
});
});
});
the result is going inside:
<div id = "details">
</div>
Try this:
$(document).ready(function() {
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#details').html('<p> Name: ' + jd.user[i].name + '</p>');
}
}
});
});
});
I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
}
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/