Insert multiple data from input Laravel - javascript

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>

Related

How to use search box to filter posts from WordPress API?

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
}
}
});
};

Javascript do not get incremented variable value instead it use defined value

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
}

Quick and simultaneous ajax call

I am currently working on add sale for POS using laravel. Here we can use barcode to scan the product code, when barcode is entered it then calls check function, if same product code is found in the cart table then it simply adds the quantity value by 1 else it make an ajax call which will return the detail of that particular product. My jQuery function looks like this:
function check() {
if ($(".product_code").length) {
var product_code = $("#product_code").val();
var total = $('#cart_contents tr').length;
$('#cart_contents tr').each(function(index) {
var p_code = $(this).find(".product_code").val();
if (product_code == p_code) {
var num = +$(this).find('.product_quantity').val() + 1;
$(this).find('.product_discount').val(0);
$(this).find('.product_quantity').val(num).keyup();
return false;
} else if (index === total - 1) {
populatecart();
}
});
} else {
populatecart();
$(".cart_content_area").hide();
}
}
function populatecart() {
var product_code = $("#product_code").val();
$.ajax({
url: "{{ url('getproductdata')}}",
data: {
p_id: product_code
},
datatype: "JSON",
type: "get",
success: function(data) {
if (data == 'null') {
alert('No product code found!');
} else {
$.each(data, function(k, v) {
$("#cart_contents").append('<tr>' +
'<td class="quantity"> {!! Form::text('sales_quantity[]', 1, ['class'=>'product_quantity form-control']) !!} </td>' +
'<td class="product_codes"><input type="text" name="product_code[]" value="' + v["product_code"] + '" class="form-control product_code" readonly/></td>' +
'<td><input type="text" name="product_name[]" value="' + v["product_name"] + '" class="form-control product_name" readonly/> </td>' +
'<td><input type="text" name="unit_value[]" value="' + v["sell_price"] + '" class="form-control unit_value" readonly/></td>' +
'<td>{!! Form::text('product_discount[]', 0, ['class'=>'product_discount form-control']) !!}</td>' +
'<td><input type="text" name="line_total[]" value="' + v["sell_price"] + '" class="form-control line_total" readonly/></td>' +
'<td class="remove_row"><input name="product_id[]" type="hidden" value="' + v["id"] + '" /><button type="button" class="removebutton" title="Remove this row">X</button></td>' +
'</tr>');
calculateTotalSum();
});
}
}
});
}
However, the problem here is that when I try to scan same product(ie; product having same product code) simultaneously it adds up the quantity but if i try the same thing really quick, the same product is populated into two different rows of the cart table but what I actually want is to have the quantity value of the product be 2 instead of creating 2 rows for same product code.
How can I deal with this problem?
rather than use callback based api.
I suggest you use promise based .
the flow goes like this.
var cart = {};
if(cart[product_code] == undefined)
{
cart[product_code] = $.ajax(url: "{{ url('getproductdata')}}" ,
data:{
p_id:product_code
},
datatype:"JSON",
type: "get");
cart[product_code].done(function(data){
//do the initialization
});
}
else
{
cart[product_code].done(function(){
//do the update.
});
}
The ajax calls may overlap.
You should probably do the check for existance in the ajax callback only, not already in check();

Counting form fields using js

I have the form that looks like this:
<form method="post" action="">
<label for="id_count-count">Count:</label>
<input id="id_count-count" type="number" name="count-count">
<div class="extrafieldWrapper"></div>
<input type="submit" value="Submit">
</form>
Depending on number of field count i add or delete new couple of fields item and item2. For example: if value of field count will be 2, it will generate two couples of fields item and item2.
There is this fields:
<label for="id_items-0-item">Item:</label>
<input id="id_items-0-item" type="number" name="items-0-item">
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="0">
<div class="extrafieldWrapperChAge"></div>
Then, depending on each value of field item2 i add new fields that calls childrenage. There is how looks childrenage field:
<label for="id_childrenage-0-childrenage">ChildrenAge 1</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
Here is fiddle link .
And here is imgur of what i want and what i've got link.
Depending of value of item2 the id of childrenage is changing too. For example if i have '3' as value of item2, then i have id_childrenage-0-childrenage, id_childrenage-1-childrenage and id_childrenage-2-childrenage. And if i have several item2 i have new examples of childrenage that count their id from the start for each item2:
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="2">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-0-childrenage">ChildrenAge</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
<label for="id_childrenage-1-childrenage">ChildrenAge</label>
<input id="id_childrenage-1-childrenage" type="number" name="childrenage-1-childrenage" value="0">
</div>
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="1">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-0-childrenage">ChildrenAge</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
</div>
In example above i have 2 fields item2, on one of it value '2' and on another value '1'. According to this i have two fields of childrenage for the first item2 with id id_childrenage-0-childrenage and id_childrenage-1-childrenage, and one field childrenage for the second with id id_childrenage-0-childrenage. But i need that count of id childrenage go on from the first item2 to the last, this is example:
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="2">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-0-childrenage">ChildrenAge</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
<label for="id_childrenage-1-childrenage">ChildrenAge</label>
<input id="id_childrenage-1-childrenage" type="number" name="childrenage-1-childrenage" value="0">
</div>
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="1">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-2-childrenage">ChildrenAge</label>
<input id="id_childrenage-2-childrenage" type="number" name="childrenage-2-childrenage" value="0">
</div>
Here is js code that realize this:
$(function(){
$('#id_count-count').on('change', function(e){
var n = $('#id_count-count').val() || 0;
var html = "<input id='id_items-TOTAL_FORMS' type='hidden' value='" + n + "' name='items-TOTAL_FORMS'>"
+ "<input id='id_items-INITIAL_FORMS' type='hidden' value='0' name='items-INITIAL_FORMS'>"
+ "<input id='id_items-MIN_NUM_FORMS' type='hidden' value='0' name='items-MIN_NUM_FORMS'>"
+ "<input id='id_items-MAX_NUM_FORMS' type='hidden' value='15' name='items-MAX_NUM_FORMS'>";
for (var i = 0; i < n; i++) {
html += "<div>Items" + (i + 1) + "</div>"
+ "<br/><label for='id_items-" + i + "-item'>Item:</label>"
+ "<input id='id_items-" + i + "-item' type='number' name='items-" + i + "-item'/>"
+ "<label for='id_items-" + i + "-item2'>Item2:</label>"
+ "<input id='id_items-" + i + "-item2' type='number' value='0' name='items-" + i + "-item2' class='children_age'/>"
+ "<div class='extrafieldWrapperChAge'></div>";
}
$(".extrafieldWrapper").html(html);
});
$(".extrafieldWrapper").on('change', '.children_age', function(e){
var n = $(this).val() || 0;
var html = "<input id='id_childrenage-TOTAL_FORMS' type='hidden' value='" + n + "' name='childrenage-TOTAL_FORMS'>"
+ "<input id='id_childrenage-INITIAL_FORMS' type='hidden' value='0' name='childrenage-INITIAL_FORMS'>"
+ "<input id='id_childrenage-MIN_NUM_FORMS' type='hidden' value='0' name='childrenage-MIN_NUM_FORMS'>"
+ "<input id='id_childrenage-MAX_NUM_FORMS' type='hidden' value='15' name='childrenage-MAX_NUM_FORMS'>";
for (var i = 0; i < n; i++) {
html += "<br/><label for='id_childrenage-" + i + "-childrenage'>ChildrenAge "+(i+1)+"</label>"
+ "<input id='id_childrenage-" + i + "-childrenage' type='number' value='0' name='childrenage-" + i + "-childrenage' />";
}
$(this).next('.extrafieldWrapperChAge').html(html);
});
});
Hope you you understand what i mean.
I am newbie in java-script, can you help me to write the code in the right way. Thanks a lot!
This particular answer was getting needlessly long, so I've decided to truncate it to just the current answer.
The Code
$(function() {
var fieldset = $('<fieldset>');
var legend = $('<legend>');
var input = $('<input>').prop('type', 'number');
var hidden = $('<input>').prop('type', 'hidden');
var label = $('<label>');
var child_wrapper = $('<div class="child-wrapper">');
/*
Here we create a couple of new HTML elements. These elements are not a part of the
HTML DOM yet and can therefore be manipulated without any visual changes.
*/
var create_hidden_fields = function(str, fields_arr) {
var ret = [];
//return array;
$.each(fields_arr, function(i, obj) {
//Loops through each field to set up the hidden values
var h = hidden.clone();
//Clones the hidden fields
h.prop('id', 'id_' + str + '-' + obj.name).prop('name', str + '-' + obj.name).val(obj.value);
//Sets the ID, name, and value.
ret.push(h);
});
return ret;
};
$('#id_count-count').on('change', function(e) {
var n = $(this).val() || 0;
//Gets the id count value, or 0;
var hidden_fields = [{
name: 'TOTAL_FORMS',
value: n
}, {
name: 'INITIAL_FORMS',
value: 0
}, {
name: 'MIN_NUM_FORMS',
value: 0
}, {
name: 'MAX_NUM_FORMS',
value: 15
}];
//Hidden fields pre-build, makes life easier, since there seems to be a pattern
var h_arr = create_hidden_fields('items', hidden_fields);
//Hidden Array created
if ($(this.form).children(':hidden')) {
$(this.form).children(':hidden').remove();
//Removes all the current hidden fields, because lazy.
}
$(this.form).prepend(h_arr); //adds in our created hidden fields.
var form = $(this.form).children('.extra-field-wrapper');
//Gets the fieldset wrapper.
form.empty();
//Empties any children there already. Otherwise extra children are added.
for (var i = 0; i < n; i++) {
var fs_clone = fieldset.clone(); //clones the fieldset element
var l_clone = legend.clone().text("Item " + (i + 1));
// clones the legend element and adds text
var la_clone_1 = label.clone();
//label clone 1
var input_clone_1 = input.clone();
//Input clone 1
var child_wrapper_clone = child_wrapper.clone().prop('id', 'parent-' + (1 + i));
//We use clones to keep our initial values safe. This way we can alter the clones without changing our defaults
fs_clone.append(l_clone);
//Adds our legend up top for readability;
la_clone_1.prop('for', 'id-items-' + i + '-item').html('Parent ' + (i + 1));
//Adds the 'for' property with the correct ID, then sets the HTML. Item and Item2 were getting confusing
input_clone_1.prop('value', 0).prop('id', 'id-items-' + i + '-item');
//Sets the default value to 0, and the necessary ID for our label to work
var la_clone_2 = label.clone().html('# of Children').prop('for', 'id-items-' + i + '-num-children');
/*
This is a lot in one line, it clones the label element, adds the HTML, and sets the property all in one.
*/
var input_clone_2 = input.clone().prop('id', 'id-items-' + i + '-num-children').prop('value', 0).addClass('children_age');
//See above comment. One difference is that this adds our class for our next function to work
fs_clone.append([la_clone_1, input_clone_1, la_clone_2, input_clone_2, child_wrapper_clone]);
//This could probably be cleaned up, but for now it works.
form.append(fs_clone); //adds the fieldset clone to the form.
} //End for
});
$(".extra-field-wrapper").on('change', '.children_age', function(e) {
var n = $(this).val() || 0;
// the current value of the item
var append_array = [];
//Add an HTML append array, lessens calls to the $(this).next().append();
$(this).before(h_arr);
//Adds the hidden elements before this element
$(this).next('.child-wrapper').empty();
//Clears the child elements
for (var i = 0; i < n; i++) {
var l_clone = label.clone().html('Children Age' + (i + 1));
var i_clone = input.clone().addClass('child-age').prop('value', 0);
append_array.push(l_clone);
append_array.push(i_clone);
//Adds the elements to the append_array since we are now done with them.
}
$(this).next('.child-wrapper').append(append_array);
//Adds all created elements;
var children_age = $('input.child-age').each(function(i, el) {
var self = $(el);
//Lazy handle
var label = $(el).prev();
//The label is the element in front of our current element.
label.text("Child Age " + (i + 1)).prop('for', 'id_childrenage_' + i + '_childrenage');
//Gives correct label number /re does the for property;
self.prop('id', 'id_childrenage_' + i + '_childrenage');
//give correct id now that changes have been made to the dom.
});
var hidden_fields = [{
name: 'TOTAL_FORMS',
value: children_age.length
}, {
name: 'INITIAL_FORMS',
value: 0
}, {
name: 'MIN_NUM_FORMS',
value: 0
}, {
name: 'MAX_NUM_FORMS',
value: 15
}];
//We have to redeclare this function here in order for the value: n to work correctly.
if ($('#id_childrenage-TOTAL_FORMS').length == 0) {
//This element does not exist yet in the DOM
var hidden_fields = [{
name: 'TOTAL_FORMS',
value: children_age.length
}, {
name: 'INITIAL_FORMS',
value: 0
}, {
name: 'MIN_NUM_FORMS',
value: 0
}, {
name: 'MAX_NUM_FORMS',
value: 15
}];
//We have to redeclare this function here in order for the value: n to work correctly.
var h_arr = create_hidden_fields('childrenage', hidden_fields);
//creates the hidden fields
$(this.form).prepend(h_arr);
} else {
$('#id_childrenage-TOTAL_FORMS').val(children_age.length);
}
});
});
label {
font-weight: 800;
}
input[type="number"] {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="">
<label for="id_count-count">Count:</label>
<input id="id_count-count" type="number" name="count-count">
<div class="extra-field-wrapper"></div>
<input type="submit" value="Submit">
</form>
The Explanation
I did a few things here, and there is more than likely a better way, but I did the best with my own time constraints.
I create the items to copy into the with jQuery because I'm old school and I just do not remember anything about how the template tag works so I stay away from it's particular variety of magics. The fieldset and legend are there solely for readability. In your actual code you can just delete their references as well as fs_clone and l_clone, instead attach the items directly to the form element.
I created a function that exists solely within the realm of our wrapping anonymous function called create_hidden_fields, as a programmer, mathematician, and all around lazy person I noticed the pattern in the naming convention and this appealed to me more than having to create and copy a bunch of items by hand every time I wanted to create a field.
I have the id_childrenage-TOTAL_FORMS (which is, by the way, the weirdest naming convention I've ever come across) to the form itself. Since we don't need more than 1 copy of the input.
The reason the hidden_fields array is redeclared in both functions is fairly simple: if it is declared before the variable n is, the TOTAL_FORMS input won't have the correct value. Not good.
Hopefully everything else can be answered by my comments in the code itself.
Happy Coding.

Get id number from a value using Jquery

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>

Categories