In this code I used JQuery with javascript first I defined room variable as 0. But inside the add_fields function I increment the room variable. add_fields function only works when user clicks a button.
But in keyup method in Jquery always gets the room as 0 because I defined it in the code. Although after I click the button and run add_fields function the room variable increased (I checked it inside the function by console.log(room)) but keyup method still see it as 0.
Help me out please.
var room = 0;
$('#room_fileds').on('keyup', '.item_name' + room + '', function() {
var query = $(this).val();
if (query != '') {
var _token = $('input[name="_token"]').val();
$.ajax({
url: "{{ route('FoodItemController.fetchNameWhenType')}}",
method: "POST",
data: {
query: query,
_token: _token
},
success: function(data) {
$('#name_list' + room + '').fadeIn();
$('#name_list' + room + '').html(data);
}
})
}
});
//set item-id when user selcts the item name from the dropdown list
$(document).on('click', '#list2', function() {
$('.item_name' + room + '').val($(this).text());
$('#name_list' + room + '').fadeOut();
});
function add_fields() {
room++;
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '<div class="form-row"><div class="form-group col"><label>Ingrediants</label><input type ="text" placeholder="Item" name="ingri[' + room + ']" class="form-control item_name' + room + ' "><div id="name_list' + room + '" style="z-index: 1;position:absolute;"></div> </div><div class="form-group col"><label>Amounts</label><input type ="text" placeholder="Amounts" name="amount[' + room + ']" class="form-control"></div><div class="col form-group"><a type="button" id="clickR[' + room + ']" class="btn-floating cyan"><i class="fa fa-check" aria-hidden="true"></i></a><a type="button" id="clickX[' + room + ']" class="btn-floating cyan"><i class="fa fa-close" aria-hidden="true"></i></a></div></div>';
objTo.appendChild(divtest);
document.getElementById('length').value = room + 1;
var hello = document.getElementById("length").value
}
Related
I'm making a quiz system. I have 3 tables:
tests table
id,
title,
total_question,
time,
status,
id_subject
questions table:
id,
content,
optA,
optB,
optC,
optD,
answer,
unit,
id_subject
questions_of_test table:
id,
id_test,
id_question
When I create a test, after I select subject, base on the number of unit of that subject will show a number of textbox to fill a number of question for each unit.
Example, the subject I selected have 3 unit. It will show 3 textboxes and I fill:
Textbox1: 1
Textbox2: 2
Textbox3: 1
Total is 10 question.
How can I insert this 10 question to questions_of_test table.
This is my some code to show texbox from dropdownlist:
$('select').select();
function get_units() {
var id = $('#id_subject').val();
var list = $('#list_unit');
list.empty();
var url = "{{ route('test.getunit', ':id') }}";
url = url.replace(':id', id);
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="form-group"><div class="col-sm-12"><input type="text" disabled value="This subject have no question" class="form-control" style="color: #26c6da;"></div></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="form-group"><label for="unit-' + result[i].unit+ '" class="col-sm-12 control-label" style="font-size: medium;">Enter number of question of unit ' + result[i].unit+ ' (have' + result[i].Total + ' questions) <span class="failed">(*)</span></label><div class="col-sm-12"><br><input type="number" min="0" max="' + result[i].Total + '" class="unit_input form-control" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].unit+ '" id="unit[' + result[i].unit+ '][]" required></div></div>';
list.append(item);
}
}
};
$.get(url, success);
}
I got an array like this:
I want to Insert random(1) where id_subject = select_id and unit = 1, random(2) where id_subject = select_id and unit = 2... How can I get it?
<input type="number" name="unit['+result[i].chuong+'][]"></input>
I have been able to get a list of posts on a php web page (outside of WordPress). How can I use the search box to filter the existing results by blog title(search term).
Here is my search box
<div class="sbox">
<h4>Search blog by title</h4>
<div class="form-group ">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by title, author or category" >
</div>
</div>
Here is my ajax attempt
$('#search_box').keyup(function(){
var text = $('#search_box').val();
var api_url_search = `http://example.com/wordpress/wp-json/wp/v2/posts?filter[s]=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var title = response[i].title.rendered;
var search_str =
'<li>'+
'<p>' + title + '</p>' +
'</li>'
;
$('#results').append(search_str);
}
}
});
});
It seems to be looping through every letter that is typed and returning all posts for each letter.
I found the answer. The WordPress api won't enable you to filter by title but you can filter by slug. So the user has to type the title with hyphens (e.g my-title)
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on keyup, start the countdown
$('#search_box').keyup(function(){
clearTimeout(typingTimer);
if ($('#search_box').val()) {
var text = $('#search_box').val();
typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
}
});
//user is "finished typing," do something
function doneTyping (text) {
// var text = text;
var api_url_search = `http://examle.com/wordpress/wp-json/wp/v2/posts?slug=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var date = response[i].date_gmt;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var categories = response[i].categories;
var search_str =
'<td>'+
'<div class="card" style="width: 300px;">' +
'<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +
' <div class="card-section">' +
'<p>' + excerpt + '</p>' +
'<h4>' + date + '</h4>' +
'<h4>' + 'Category:' + categories + '</h4>' +
'<a href="http://example.com/api-posts.php?">'+
'<input type="button" value="read more">' + '</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'
;
$('#results').empty().append(search_str); // empty previous results and append new results
}
}
});
};
I'm wanting to get the key value pair for a the specific div, and only the div that I click on. Right now it is logging the values for each div. How can I get only the value for the specific div that I am clicking on? I'm wanting to update during an ajax success, but I'm stumped as to how to update only a certain div. Any ideas as to how I can do this?
$('.wrapper').on('click', '.bet-button', function() {
var self = $(this);
var gameId = self.attr('gameid');
var awayVal = $('#' + gameId + ' input[name=betAmountAway]').val();
var homeVal = $('#' + gameId + ' input[name=betAmountHome]').val();
var awayId = $('#' + gameId + ' .bet-input-away').data('away-id');
var homeId = $('#' + gameId + ' .bet-input-home').data('home-id');
var pointTotals = $('#' + gameId + ' .total-points').val();
console.log(pointTotals);
var value = awayVal || homeVal;
var id, value;
if (awayVal) {
id = awayId;
value = awayVal;
}
if (homeVal) {
id = homeId;
value = homeVal;
}
if (!value) {
alert('please enter a value!')
} else {
$.ajax({
url: "---------" + userId + "/"+ gameId +"/"+ id +"/"+ value +"",
type: "get",
success: function(response) {
// Makes the inputs inputable again.
$('.bet-input-home').prop('disabled', false);
$('.bet-input-away').prop('disabled', false);
function update(){
var currentSelection = $('#team-select').val();
getGames().done(function(results){
$.each(results, function (i, gameData){
$.each(gameData, function(key, game){
var gamesHome = game.home_team_conference;
var gamesAway = game.away_team_conference;
if(gamesHome == currentSelection || gamesAway == currentSelection){
var gameId = game.id;
var pointTotal = game.total_points_bet;
var gameTime = game.game_time_hour;
var gameDate = game.game_time_date;
var homeId = game.home_team.id;
var awayId = game.away_team.id;
var homePoints = game.total_points_bet_on_hometeam;
var awayPoints = game.total_points_bet_on_awayteam;
var totalPoints = homePoints + awayPoints;
// $('#point-total').append(homePoints + awayPoints);
}
});
});
})
}
update();
This updates html code that is generated dynamically (or at least it is supposed to)
$('.wrapper').append('\
<div id="'+ gameId +'" class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
<div class="game-cards">\
<div class="chart-container">\
<canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
</div>\
<div class="right-info">\
<h4>' + awayTeam + '<br>' + " # " + '<br>' + homeTeam +'</h4>\
<h5 id="time-channel">'+ gameDate +' # ' + gameTime + '<br>' + ' On ' + network +'</h5>\
<div class="total-points-live">\
<h5>Total Points Bet</h5>\
<h5 class="total-points" id="point-total">'+ totalPoints +'</h5>\
<p>'+ awayTeam +'</p>\
<input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
<p>'+ homeTeam +'</p>\
<input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
<p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
</div>\
</div>\
</div>\
');
I have the following code :
var currentuuid = $('#UUIDTOSEND').val();
html1 = '';
$.ajax({
type: "GET",
url: "database/Emarps/websrvc/websrvc.php?task=getData&UUID=" + currentuuid + "&DataGt=stitrtmnt",
dataType: "JSON",
success: function (data) {
client_history_list = $('#clinical_history_tbody').empty();
for (i = 0; i < data.length; i++) {
html1 += '<tr>\n\
<td class = "form-group">\n\
\n\
<input type = "text" class = "form-control facility_name col-md-6 col-sm-6 col-xs-12 " readonly="" name="facility_name[]" id = "facility_name" value="' + data[i].facility_name + '" placeholder = "Facility Name">\n\
</td>\n\
<td class = "form-group">\n\
\n\
<input type = "text" class = "form-control activity_timestamp col-md-6 col-sm-6 col-xs-12 " readonly="" name="activity_timestamp[]" id = "activity_timestamp" value="' + data[i].activity_timestamp + '" placeholder = "Visit Date">\n\
</td>\n\\n\
<td class = "form-group">\n\<input type = "text" class = "form-control clinical_visit_id' + data[i].id + ' " readonly="" name="clinical_visit_id[]" id = "clinical_visit_id" value="' + data[i].id + '" placeholder = "Visit ID">\n\
\n\
<button id="view_more' + data[i].id + '" class="form-control view_more' + data[i].id + '" >Select/View More</button>\n\
</td>\n\
</tr>';
$("#clinical_history_tbody").on("click", ".view_more" + data[i].id, function () {
var clinic_visit_ids = $("#" + this.id.replace("view_more", "clinical_visit_id")).val();
alert(clinic_visit_ids);
});
}
$('#clinical_history_tbody').empty();
$('#clinical_history_tbody').append(html1);
}
});
Which generates an auto table with data from the database.
I want to get the value of id from the button when I click the Select/View More button, which runs the following the $("#clinical_history_tbody").on("click", ".view_more" + data[i].id, function () { function on the script. How can I get the value of the button id and replace it so that I can use it in the clinic visit ? (When I alert I get an undefined).
The input for "clinical_visit" is never assigned a numeric value at the end of its id.
<input type = "text" class = "form-control clinical_visit_id' + data[i].id + ' " readonly="" name="clinical_visit_id[]" id = "clinical_visit_id" value="' + data[i].id + '" placeholder = "Visit ID">
it is instead concatenated to its class.
this goes wrong when you are tring to fetch the "clinical visit" field, since you are looking for an id with value "clinical_visit_id[number]".
It isn't there, so you end up with an empty value :
var clinic_visit_ids = $("#" + this.id.replace("view_more", "clinical_visit_id")).val();
try this :
<input type = "text" class = "form-control clinical_visit_id' + data[i].id + ' " readonly="" name="clinical_visit_id[]" id = "clinical_visit_id'+data[i].id+'" value="' + data[i].id + '" placeholder = "Visit ID">
OR
look for the "clinical_visit" input by class instead of id (keep in mind you still need to sanitize your HTML, since two elements should never have the same id
That would look like this :
$("#clinical_history_tbody").on("click", ".view_more" + data[i].id, function () {
var clinic_visit_ids = $("." + this.id.replace("view_more", "clinical_visit_id")).val();
alert(clinic_visit_ids);
});
You can use this script to get the id,
$("#clinical_history_tbody").on("click", "[class^=view_more]", function () {
alert($(this).attr("id"));
});
the above script wll bind click event to all the elements whose class name starts eith view_more. Then it will alert the current clicked elements id.
This is how you change the id of the button:
$("#clinical_history_tbody").on("click", function () {
var clinic_visit_ids = $(this).attr('id', "clinical_visit_id");
});
Attach event to that button onClick
onClick=giveMeID(data[i].id)
in Html and then define in JS
function giveMeID(id){
//Do whatever you want
}
Here's Example JSBIN DEMO
<html>
<body>
<button id="exa" onclick="genExamp()">Generate Example</button>
<div id="ex"></div>
<script>
function genExamp(){
var divEx = document.getElementById("ex");
for (var i = 0; i < 20; i++) {
var childBtn='<button id="view_more'+i+'" onclick="giveMeID('+i+');">View/More'+i+'</button>';
divEx.innerHTML+=childBtn;
}
}
//On Click:Gets ID and Replace it
function giveMeID(obj){
var origID="view_more"+obj;
var btn=document.getElementById('view_more'+obj);
btn.id="view_more"+obj*10;
var new_id=btn.id;
alert("Original ID:"+origID+"\n"+"New ID:"+new_id);
}
</script>
</body>
</html>
I have a page that uses a couple of AJAX calls to get and update data. A user enters a product number in an input box, then clicks a <button>, which runs a function that has a jQuery AJAX call to populate a div. See below.
HTML
<form rol="form">
<div class="form-group">
<label for="sku" id="sku-label">Please enter the SKU below</label>
<input class="form-control text-center" type="input" id="sku">
<button class="btn btn-primary col-md-12" type="button" id="bClick" onclick="getSku( $( '#sku' ).val() );">Get SKUs</button>
</div>
<input type="hidden" id="badgeNum" value="<?php echo $_SESSION['BADGE_NUMBER']; ?>">
</form>
<div class="col-md-12" id="sku-results"><!--This div gets populated. -->
</div>
jQuery
function getSku(sSku) {
//AJAX call to get SKUs goes here.
$.ajax({
type: 'POST',
url: 'sku-query.php',
async: false,
mimeType: 'json',
//dataType: 'application/json',
data: {sku: sSku},
success: function(data) {
var disp = "";
disp += "<div class='col-md-12' id='skuDisplay'>";
disp += "<div class='col-md-2'><strong>SKU</strong></div>";
disp += "<div class='col-md-3'><strong>Description</strong></div>";
disp += "<div class='col-md-2'><strong>Master</strong></div>";
disp += "<div class='col-md-2'><strong>Daughter</strong></div>";
disp += "<div class='col-md-2 text-center'><strong>Location</strong></div>";
disp += "<div class='col-md-1 text-center'><strong>Update</strong></div>";
disp += "</div>";
counterp = 0;
$.each(data, function(i, data) {
disp += "<div class='col-md-12' id='skuDisplay'>";
disp += "<div class='col-md-2' id='dSku' >" + data[0] + "</div>";
disp += "<div class='col-md-3' id='dDesc'>" + data[1] + "</div>";
disp += "<div class='col-md-2' id='dMast'>" + data[2] + "</div>";
disp += "<div class='col-md-2 text-center' id='dDaughter'>";
disp += "<input class='col-md-6 text-center' type='number' value='"+ data[3] + "' id='dChange'>";
disp += "</div>";
disp += "<input type='hidden' id='oldQty' value='" + data[3] + "'>";
disp += "<div class='col-md-2 text-center' id='dLoc'>" + data[4] + "</div>";
disp += "<div class='col-md-1 text-center'><a class='inv-click' id='" + counterp + "' onclick='updateDaughter(this.id)' value='" + counterp + "'><i class='fa fa-check-square-o'></i></a></div>";
disp += "</div>";
counterp = counterp + 1;
});
//Success function if all goes well.
$( "#sku-results" ).empty();
$( "#sku-results" ).append( disp );
},
error: function() {
alert('There seems to be an error fetching SKUs.');
}
});
}
So the above code works fine. In each div that is appended to the page, there is an <a> element. The purpose of these divs being added is that each div has an input box where the user can change a value. When the value is changed and the a element is clicked, another function, with another AJAX call is run. When the second AJAX call in this function is done running, I need to then run the first function AGAIN to update the page with the updated value. See the second function below.
function updateDaughter(getId)
{
var master = $( "#" + getId ).closest("#skuDisplay").children("#dMast").html();
var daughter = $( "#" + getId ).closest("#skuDisplay").children("#dDaughter").children("#dChange").val();
var loc = $( "#" + getId ).closest("#skuDisplay").children("#dLoc").html();
var oldQty = $( "#" + getId ).closest("#skuDisplay").children("#oldQty").val();
var emp_id = $( "#badgeNum" ).val();
var sku = $( "#" + getId ).closest("#skuDisplay").children("#dSku").html();
var dDate = new Date();
var dDay = ("0" + dDate.getDate() ).slice(-2);
var dMonth = ("0" + dDate.getMonth()).slice(-2);
var dYear = dDate.getFullYear();
var dHour = ("0" + dDate.getHours() ).slice(-2);
var dMin = ("0" + dDate.getMinutes()).slice(-2);
var dSec = ("0" + dDate.getSeconds()).slice(-2);
var dFullDate = dYear + "-" + dMonth + "-" + dDay;
var dFullTime = dHour + ":" + dMin + ":" + dSec;
var dAllDate = dFullDate + " " + dFullTime;
var move_from = "Adjustment";
//var created = date('Y-m-d h:i:s');
var worktype = "Reslot";
var qty = daughter - oldQty;
alert("DATE:" + dAllDate + ". SKU:" + sku + ". MASTER:" + master + ". LOC:" + loc + ". DAUGHTER:" + daughter + ". OLD:" + oldQty + ". EMPID:" + emp_id + ". QTY:" + qty + ". MOVEFROM:" + move_from + ". TYPE:" + worktype);
var workTypeId = "";
if (worktype = 'Putaway') {workTypeId = 1;}
if (worktype = 'RTI') {workTypeId = 2;}
if (worktype = 'Replen') {workTypeId = 3;}
if (worktype = 'Manual Replen'){workTypeId = 4;}
if (worktype = 'Reslot') {workTypeId = 5;}
if (worktype = '01 Replen') {workTypeId = 6;}
if (worktype = '03 Replen') {workTypeId = 7;}
if (worktype = '02 Replen') {workTypeId = 8;}
$.ajax({
type: 'POST',
url: 'http://a/location/that/works',
async: false,
data: JSON.stringify({
workTypeID: workTypeId,
completedDate: dAllDate,
startLocation: move_from,
endLocation: loc,
quantity: qty,
assignedAdministratorID: emp_id,
createdDate: dAllDate,
startedDate: dAllDate,
createdAdministratorID: emp_id,
sku: sku
}),
contentType: 'application/json',
success: function(data) {
if(data.status == 'Success') {
$('#result').text(data.status);
} else {
$('#result').text('Failed on update: ' + data.status + ', ' + data.errorMessage);
}
},
error: function() {
$('#result').text('There might be some problem on the web service. Please contact administrator.');
}
});
$( "#bClick" ).click();
}
What's the problem?
The second function works in that it updates the corresponding database with the information that it needs to update it with. The problem is that I cannot get my page to then reload with the updated information. After I change the value and click the <a> tag, the page runs the first function again but the old value shows up. The only way I can get the new value to show up is if I click on the button with the same product number again.
Upon reading about this, I came across that AJAX will run its own process apart from the rest of your function. So in my second function, if I am calling my first function again, what looks like is happening is that my first function is being called in my second function before the AJAX call is even done.
What I tried
-I figured that I would try adding async: false to both of my jQuery AJAX functions, which did not work.
-I tried running my first function in my second function in various places. Inside of the AJAX success parameter, after the AJAX call altogether, etc... This did not work either.
-I tried to patch this by replacing the old value with the new value in the input box manually (empty() then append()) just to show the user than their changes have "updated", but even this gets overwritten by the old data (which is not even there anymore because of the second AJAX call). The AJAX call is getting "outraced" by the rest of the function, it seems.
-I tried just triggering the button to be "clicked" again inside, and after the second AJAX call by $( "#bClick" ).click();. Same thing. Didn't work.
What I need
This is what I need to happen:
-The user types a product number (works)
-The user clicks a button (works)
-The button triggers a function that runs an AJAX call to populate the page with info; each row of info has an input box with a number that can be changed, and an <a> button that will run another function. (works)
-When the <a> button is clicked, another function is run that has another AJAX call that updates a database with information, including the changed value in the input box. (works)
-Inside of the second function, after the AJAX call is run, the first function with the first AJAX call should be run again to update the page with the changed information. (does not work)
Can someone help me figure this out?