I just want to ask how to get the selected value from appended select list using jquery. Please help me. Thanks in advance.
var wrapper1 = $(".column1");
array1 = ["sample1", "sample2", "sample3"];
var myRoot = window.location.origin + "/";
$.ajax({
url: myRoot + 'Payslip/GetDataFromAppend',
type: 'GET',
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ id: $this }),
async: true,
success: function (data) {
$(wrapper1).append(appendOption(data, array1[0]));
}
});
var appendOption = function (data, txtData) {
var appendfor = '<label class="col-sm-4 control-label"><label> ' + txtData + '...</label></label><div class="col-sm-7">' +
'<select class="form-control" asp-for="PayslipID" asp- items="ViewBag.PayslipID" data- val="true" data- val - required="The Payslip ID field is required." id= "PayslipID" >';
for (var i = 0; i < data.length; i++) {
console.log(data[i].value);
appendfor += '<option value="' + data[i].value + '">' + data[i].value + '</option>';
}
appendfor += '</select ></div >';
return appendfor;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group column1"></div>
The 'form-control' element is added to the page dynamically so you need to use event delegation, try this:
$(document).on('change', ".form-control", function(){
alert($(this).val())
});
'column1' should also work in place of 'document' assuming that it is a static element.
Related
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
postContent = entry[i].content.$t;
content = '<div class="contentWrap"><div id="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
}
}
});
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
#close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'>
</div>
How to load post content only when clicking the title?
I can use .toggle in jquery but I need to load and "unload" content, not just showing and hiding it. I hope i'm making sense.
My skill is limited to css only, thank you for your help.
You can use display:none to <div class="contentWrap"> and on click of a tag you can show the content using closest() and next().And on click of close again use "display", "none" to hide that content div .
Demo Code :
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
postContent = entry[i].content.$t;
//added display none and added class = close
content = '<div style="display:none"class="contentWrap"><div class="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
}
}
});
//on click of a tag show content
$(document).on("click","a",function(){
//a->closest div->next content->show
$(this).closest(".items").next(".contentWrap").css("display", "block");
})
//onclick of close -> hide again
$(document).on("click",".close",function(){
$(this).closest(".contentWrap").css("display", "none");
})
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
.close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'>
</div>
Update 1 :
You can assign i value some custom attribute and then use same index value to access post content.In below code snippets i have not send again request to server to load json on click of a instead i have use some variable to store content of data.feed.entry in some variable and then use this to add content .
Demo Code :
var datas = "";
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
//adding entry content in datas to use later
datas = data.feed.entry;
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
//passing index no i.e : " i " in custom attribute
items = '<div class="items"><h2><a data-val=' + i + ' href="#' + postTitleLink + '">' + postTitle + '</a></h2></div>';
document.getElementById('showlists').innerHTML += items;
}
}
});
$(document).on("click", "a", function() {
$(".contentWrap").remove(); //remove previous div
var ids = $(this).attr('data-val');
console.log(ids)
//getting data that index position got from a tag
postTitle = datas[ids].title.$t;
postTitleLink = datas[ids].title.$t.replace(/\s+/g, '-').toLowerCase();
postContent = datas[ids].content.$t;
content = '<div class="contentWrap"><div class="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
})
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
.close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showlists"></div>
I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>
First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.
I want to add input whit js and send value whit jQuery but value dosnt send.
Actually fields value dosn't define in jQuery.
function addElement(myDiv, type) {
var ni = document.getElementById(myDiv);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my' + num + 'Div';
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<input class="name" name="name[]" value="" placeholder="عنوان"><input class="value" name="value[]" value="" placeholder="توضیحات"><input type="hidden" class="type" name="type[]" value="' + type + '"><input type="hidden" class="position" name="position[]" value="' + myDiv + '">'
ni.appendChild(newdiv);
}
$('#add_field').live('click', function() {
var id = $('#id').val();
var name = $('#name').val();
var value = $('#value').val();
var type = $('#type').val();
var position = $('#position').val();
var name = [];
var value = [];
var type = [];
var position = [];
$(".name").each(function() {
name.push($(this).val());
});
$(".value").each(function() {
type.push($(this).val());
});
$(".position").each(function() {
size.push($(this).val());
});
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: {
name: name,
type: value,
size: type,
position: position
},
success: function(data) {
$('#result').html(data);
}
});
});
PHP
print_r($_POST['name']);
print_r($_POST['value']);
print_r($_POST['type']);
print_r($_POST['position']);
echo $_GET['id'];
Notice: Undefined index: name
Notice: Undefined index: value
Notice: Undefined index: type
Notice: Undefined index: position
Use this ajax. Note that the $('form') selector needs to be a valid selector that targets your <form> tag. If you serialize, the arrays will be passed as arrays in HTTP, not as a javascript array value. With this mode, PHP will recognize them as arrays, not as [OBJECT object] value
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: $('form').serialize(); // that's the change
success: function(data) {
$('#result').html(data);
}
});
EDIT
Test with serializeArray():
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: $('form').serializeArray(); // that's the change
success: function(data) {
$('#result').html(data);
}
});
More info: https://api.jquery.com/serializeArray/
EDIT 2
As I said in comments, you can make it with serialize():
http://jsfiddle.net/tZPg4/15519/
It works perfectly.
I have the following jquery funcion that's supposed to get a value from a text field:
My Php Code
function asset_status() {
$query = $this->db->query("SELECT count(job_card_no) as job_card_no,number,asset.type,asset.status,asset.id as asset_id FROM asset inner join assgnd_rsces on assgnd_rsces.name = asset.id inner join job_card on job_card.id = assgnd_rsces.job_card_id");
$result = $query->result_array();
echo json_encode($result);
}
ajax request
asset_status_list = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>operations/asset_status",
dataType: "JSON",
success: function (response) {
console.log(response); // it gives following
//job_card_no "2" number "1" status "Active" type "Toilet"
for (i = 0; i < response.length; i++) {
asset_status_list = '<tr><td >' + response[i].job_card_no + '</td><td >' + response[i].number + '</td><td>' + response[i].type + '</td><td ><input type="hidden" name="view_more_id" class="view_more_id' + response[i].id + '" id="view_more_id" value="' + response[i].id + '"/><button id="view_more_link" class="view_more_link' + response[i].id + '"><i class="glyphicon glyphicon-zoom-in "></i>View More</button></td></tr>';
$('#asset_status_tr').append(asset_status_list);
$("#asset_status_tr").on("click", ".view_more_link" + response[i].id, function () {
var asset_id = $(".view_more_id"+response[i].id).val();
alert(asset_id);
});
}
$('#asset_table_status').DataTable({});
},
error: function (response) {
}
});
However when I try it using the above function, I get the following error on click of the button.
TypeError: response[i] is undefined
var asset_id = $(".view_more_id"+response[i].id).val();
How do I solve the above error ?
Yes, you are not getting 'json' from file that's why its length is 0 and its shown you 'undefined'.Please make sure that.
Ok i have some search results from input box. I used keyup to get results. Then tis results send to AJAX, and i want to append it to table. My problem is because i use append i will get more than one table headers if i have more results, on the other side i cant use html() because script use for loop so i will only get one result. Can someone help me to solve this problem. I try something like this...
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);;
$('#result').html('');
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
$('#result').append('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody><tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr> </tbody></table> ' );//dodavanje rezultata u div
}
}
})
}
});
Just create the table once and then append trs in the loop to its tbody
$('#warning').html(response.msg);
if (response.result.length) {
var $table = $('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody></tbody></table>').appendTo($('#result').html(''));
var $tbody = $table.find('tbody');
for (var i = 0; i < response.result.length; i++) //petlja za pristup json
{
$tbody.append('<tr><td>' + response.result[i].id + '</td><td>' + response.result[i].naslov + '</td><td>' + response.result[i].autor + '</td><td>' + response.result[i].cena + '</td><td>' + response.result[i].valuta + '</td></tr> '); //dodavanje rezultata u div
}
} else {
$('#result').html('')
}
Try this :
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);
// Store jQuery objects if used more than once
var $table = $('<table class="page-list">').appendTo($('#result')),
$thead = $('<thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead>').appendTo($table),
$tbody = $('<tbody>').appendTo($table);
innerHTML = '';
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
innerHTML += '<tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr>' );//dodavanje rezultata u div
}
// Append to HTML only once, when you have the full HTML to append
$tbody.append(innerHTML);
}
})
}
});