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>
Related
Here is javascript code to add input field in on click but while storing only one row is stored . How to store all the row?
<div class = "row" id="dynamic_field">
<div class = "input-field col s12">
<input id = "list-title" name = "post[title]" type = "text" class = "validate" required value = "<">
<label for = "list-title ">Title</label>
</div>
</div>
$(document).ready(function() {
$('#added').click(function () {
$('#dynamic_field').append('<div class="row">' +
'<div class = "input-field col s12" >\n' +
' \n' +
'<input id = "list-title " name = "post[title]" type = "text" class = "validate" required value = "">\n' +
'<label for = "list-title ">Title</label>\n' +
'</div>'+
'</div>'
);
});
});
Here is my php code in store controller.
public function UpdateController() {
if (isset($_POST['post'])) {
$data = $_POST['post']
$model->title = $data['title'];
}
$model->save();
}
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 am working on a Trello Board using Vanilla Javascript and I am receiving an error on making my Cards . I have used Local and Session Storage to store the cards and lists respectively but I can't figure out why this error persists after I click on the Add Card Board Button
function newTask(x){
card_index= parseInt(localStorage.getItem("card_indices")) ;
//card_index = parseInt(sessionStorage.getItem("card_indices"));
list_index = parseInt(sessionStorage.getItem("index"));
document.getElementById('myTasks').innerHTML +=
'<div id = "list_' + list_index + ' " class="list-item animated zoomIn" > <h2 id = "title_' + list_index +'" onClick = "modifyObj.titleEdit('+ list_index +')" class="list-item__h2">'+x+'</h2><span id = "span_del_' + list_index + '" class ="btn title-delete" onClick ="modifyObj.titleDelete(' + list_index + ')">\u00D7</span><hr>'+
'<input id = "card_del_' + card_index + '" type="text" class="myInput" placeholder="Title...">' +
'<div class="btn add-items " id = "div_add_list_" onClick = "myCard.titleForm(' + list_index + ',' + card_index + ')" >Add List Item</div>'
'</div>'
sessionStorage.setItem("index", parseInt(sessionStorage.getItem("index"))+1);
}
var myCard = {
card:function(index, card_index){
var enteredElement = document.getElementById('card_del_' + card_index).value;
var textNode = document.getElementsByClassName('text_' + card_index);
textNode.innerText = enteredElement;
if (enteredElement === ""){
alert("You must write something ");
}
else{
document.getElementById("text_").style.display = "block";
}
},
titleForm: function(index,card_index){
element = document.getElementById('card_del_' + card_index);
text = '<li style="display:none" class="text_'+ card_index +'"> <span class = "btn items" onClick = "myCard.cardClose()">u00D7</span></li>'
element.insertAdjacentHTML('beforeend', text);
myCard.card(index,card_index);
localStorage.setItem("card_indices", parseInt(localStorage.getItem("card_indices"))+1);
// card_index+=1;
}};
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
}
How can I pass object to inline onclick event. When I try following code I either get undefined or [object object].
also how can I bind click event to h to avoid inline code.
this.get = function(o) {
console.log(o, o.foo);
}
this.somefunction = function(robj) {
for (var i = 0, i <= robj.length; i++) {
var fname = robj[i]['filename']
h += '<div class="checkbox checkbox-success" onclick="get(\'' + robj + '\')">' +
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>' +
'</div>';
}
}
A few problems I saw with your code,
your loop should be i < robj.length and has a syntax error , should be ;
h was not defined but now not used anymore
The array passed into get() cannot be accessed by using o.foo
Side note: take a look at ES6 template literals to help clean up some of the quoting action you are currently doing, for example id="' + fname + '" can look like id="${fname}"
Here is a full working example with the fixes above on how you can add a listener to your div (by creating DOM element) and with the object as a parameter.
this.get = function(o) {
console.log(o);
console.log(o.foo);
}
this.somefunction = function(robj) {
for (let i = 0; i < robj.length; i++) {
var fname = robj[i]['filename']
var myDiv = document.createElement("div");
myDiv.className = "checkbox checkbox-success";
myDiv.onclick = function(){get(robj[i])};
myDiv.innerHTML =
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>';
document.getElementById("container").appendChild(myDiv);
}
}
var robj = [{filename: "myFilename", foo: "myFoo"}]
somefunction(robj);
<div id="container"></div>
here is an example of dynamically written onclick . simply keep the function outside of doucment.ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changePath(distinct_inputs)
{
console.log(distinct_inputs);
}
$(document).ready(function(){
var distinct_inputs = 0;
$('.icon1').click( function(){
distinct_inputs = distinct_inputs + 1 ;
$('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});
});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>
</body>
</html>