Populate Bootstrap modal form fields from JSON - javascript

I've got a Bootstrap modal that displays a large form (30+ inputs).
I wrote the following code to populate the first few fields from JSON.
$('#seg-detail-modal').on('shown.bs.modal', function (e) {
var modal = $(this);
$.get( "includes/segdata.json", function( data ) {
$('#seg-detail-modal').find("input[name='segCode']").val(data.segCode);
$('#seg-detail-modal').find("input[name='orgName']").val(data.orgName);
$('#seg-detail-modal').find("input[name='referenceId']").val(data.referenceId);
});
});
Is there a more efficient way of populating a large form than what I'm doing here?

You could just iterate through the object properties and match selector to property in that loop.
Something like:
$('#seg-detail-modal').on('shown.bs.modal', function(e) {
var $inputs = $(this).find(':input');
$.getJSON("includes/segdata.json", function(data) {
$.each(data, function(key, val) {
$inputs.filter('[name="' + key + '"]').val(val);
});
});
});
If a property exists that doesn't have a match the selector will just fail quietly

Related

Show message in div after saving

I save some data in my MYSQL database, after saving I wan't to show a text in my div with id #msg. Can somebody help me.
<script>
$(document).ready(function () {
$("#btnAdd").click(function (e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
var afspraken = $('#afspraken').val();
var coachings_id = $('#coachings_id').val();
var verlengen = $('#verlengen').val();
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
$("form")[0].reset();
});
return false;
});
});
</script>
Just use the .html( ) method on your #msg div:
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
$( "#msg" ).html( data );
$("form")[0].reset();
});
This is assuming the data variable is a simple string. If it's JSON you'll want to use JSON.parse( data ) to convert it back to an object, and then print out the properties you need.
You have few options todo this, for example You can control visibility by CSS.
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
// place code here to manipulate showing the notification div
});
For manipulate code, You can write:
document.getElementById('#msg').style.visibility = 'visible' or 'hidden'
visible or hidden is depend on what You want todo with your #msg element.

Getting Data from button click for Jquery

I am using the "Second Solution" from this problem:
call the same jQuery function in multiple buttons
I am dynamically creating my buttons, based on an input, so there is currently 45 buttons! (used to select page number)
Is there a way to use the value of the button as data in my $.get so I can pull the data for the page?
$('.bclick').click(function(){
$.getJSON("url", { page: [need button data here] }, function(data){
//Some actionable code
})
});
.bclick is the class given to each of the buttons created.
when you are inside of the function, the reserved word this is a reference to your clicked button.
$('.bclick').click(function(){
var page = $(this).val();
$.getJSON("url", { page: page }, function(data){
//Some actionable code
})
});
If your buttons are created dinamically probably this solution won't work. I may suggest you to use $.on():
$("parent selector or form selector").on("click", ".bclick", function(){
var page = $(this).val();
$.getJSON("url", { page: page }, function(data){
//Some actionable code
})
})
If you are generating buttons dynamically, then use .on.
$(function(){
$(document).on("click", ".blick", function(){
var $this = $(this);
var buttonName = $this.attr("name");
});
});
Sample code
Yes you can by adding an extra attribute to your .bclick element, for example
<button class="bclick" data="your data here"></button>.
Then
$('.bclick').click(function(){
var buttonData = $(this).attr('data');
$.getJSON("url", { page: buttonData }, function(data){
//Some actionable code
})
});

How to remove elements from jquery object

I have a specific problem. I want to grab some element, traverse through it and remove or edit unwanted elements before posting that element data over JSON.
My function looks like this.
$("#submit_btn").off("click").on("click", function(e) {
e.preventDefault();
pdfhtml = $("#Calculation").html();
var inputs = $("input[type=number]", pdfhtml);
$.each(inputs, function(k, v) {
$(this).remove();
//$(this, pdfhtml).remove(); //also not working
})
var data = {};
data["data"] = pdfhtml;
alert(pdfhtml);
getdataJSON("","POST", "html", data, true);
});
The problem I have is that nothing happens, elements are still present after i submit this data. What am I doing wrong? I need this in order to generate pdf with mpdf6 (PHP).
You are creating a temp jQuery object and is removing inputs form that but the original string pdfhtml is not modified
$("#submit_btn").off("click").on("click", function (e) {
e.preventDefault();
//create a temp dom structure with the target html as its content
var $temp = $('<div />', {
html: $("#Calculation").html()
});
//modify the temp dom structure
$temp.find("input[type=number]").remove();
var data = {};
//get the update html content from the temp object
data["data"] = $temp.html();
alert(pdfhtml);
getdataJSON("", "POST", "html", data, true);
});
jQuery won't do string modification like that. All inputs will be is an in-memory representation of <input> tags, changes to these will not save back to the pdfhtml string.
What you should do instead is clone the #Calculation div, then perform your actions:
$("#submit_btn").off("click").on("click", function(e) {
e.preventDefault();
var pdfhtml = $("#Calculation").clone(); // Clone this
var inputs = pdfhtml.find("input[type=number]");
$.each(inputs, function(k, v) {
$(this).remove();
});
var data = {};
data["data"] = pdfhtml.html(); // Read the HTML here...
alert(pdfhtml);
getdataJSON("","POST", "html", data, true);
});

pass data to modal using javascript

I am creating a website in MVC5 using bootstrap with the boostrap tables library http://wenzhixin.net.cn/p/bootstrap-table/docs/index.html
using:
$('#subscriber-table').on("click-row.bs.table", function (e, row, $element) {
console.log(row.SubscriberID);
$('#subscriberDialog').modal();
});
I receive the click on one of the table's records. This works great ony now I want to pass the json object called row to my created modal, so I can set the name input field. Like this:
$('#subscriberDialog').on('show.bs.modal', function (event) {
$('#namefield').val('toSetName');
});
I have been trying to figure this out but I cant seem to get it to work.
What you can do you can set any custom attribute in modal to get the value.
like this :
$('#subscriber-table').on("click-row.bs.table", function (e, row, $element) {
console.log(row.SubscriberID);
$('#subscriberDialog').attr('data-custom-value', 'toSetName');
$('#subscriberDialog').modal();
});
$('#subscriberDialog').on('show.bs.modal', function (event) {
var val = $(this).attr('data-custom-value');
$('#namefield').val(val);
});
Pass Through array also like OnClick(['a','b','c']);
and Retrieve Like
function checkData(value)
{
alert(value[0] + " " + value[2] .....);
}

Generate input handler via jQuery for xmlhttprequest json data in a table

I'm struggling with dynamic generation of buttons over a JSON array.
Stripped-down code is this (aim is to build a table based on the data, nothing fancy yet, I'm not yet proficient at this):
$.ajax({
/* type, content, etc. removed */
success: function (data, textStatus, XmlHttpRequest) {
var target = $('myContainerDiv');
var result = data.d.results;
var $table = $('<table />');
for(var i=0;i < results.length; i++) {
var $row = $('<tr />');
var $cell = $('<td />');
var $button = $('<input />').attr({ type: 'button', value: 'Edit', name: 'btn' + i });
$button.click(function () {
// **
// In a .NET environment, this would become a closure
// I suspect this is the offending bit of code
//
alert(results[i].name);
};
$cell.append($button);
$row.append($cell);
$table.append($row);
}
$target.append($table);
},
/* error etc. removed*/
});
I basically want a column filled with buttons, each one would popup the value of a field from the array I get from my $.ajax call.
Buttons actually show up, but they do not react to clicking, and I see no runtime error in the F12 tools console. This is probably due to the fact that this script is part of the configuration page for a Microsoft Dynamics CRM 2011 Solution, but other than that, I'm sure the AJAX call goes on OK (I tried making it print out data, and I can see it).
UPDATE
Referencing i inside the click handler was the offending line indeed: changed the code like this made things work as I was expecting:
var $button = $('<input />').attr({ type: 'button', value: 'Edit', name: 'btn' + results[i].name });
$button.click(function () {
// 'i' value is NOT what I thought it was !
alert(this.name.substring(3,this.name.length));
// I found out in the meanwhile that 'this' references the event source
};
First you have several syntax errors in your code and it may not be running at all:
if the ID of your div container is myContainerDiv, to get the target you need to do $('#myContainerDiv')
you create a result varialbe, but you use a results variable
you're not closing the parentesis in the $button.click
you're adding everything to $target but is defined as target
Now the actual problem may be, as you say, the closure, remember that you close over variables not values, so when you execute the button click handler, i has a value of results.length, so you are out of bounds by that time.
You could try to store the results objects elsewhere, extract the Id of the object your looking for from the button (you're naming then 'btn'+i) and then access the name property that way.
I noticed you didn't close the .click() bracket.
Try...
$button.click(function () {
alert(results[i].name);
});
You can try this ...
$.ajax({
/* type, content, etc. removed */
success: function (data, textStatus, XmlHttpRequest) {
var $target = $('#myContainerDiv'),
results = data.d.results,
$table = $target.append('<table />').children('table:last-child'), $trSet = $([]);
for(var i=0; i < results.length; i++) {
$trSet = $trSet.add(
$([
'<tr><td>',
$('<input type="button" value="edit" name="btn'+i+'" rel="'+results[i].name+'" />').wrap('<div />').html(),
'</td></tr>'
].join(''))
);
}
// Using Event delegation ... Only one handler is attached to the DOM.
$table.append($trSet).click(function(e){
var $t = $(e.target);
if( $t.is('input[type="button"]') ){
alert($t.attr('rel'));
}
// choose to return false whether to prevent event bubbling up the DOM or not
// return false;
});
},
/* error etc. removed*/
});

Categories

Resources