I am Using datatable js in MVC4. I want to generate modal popup on each row creation when table is create with data fill and open each modal popup on each radio button click.
$('#Hotel').dataTable({
bDestroy: true,
bProcessing: true,
sAjaxSource: '#Url.Action("SelectHotel_TripInfo", "CL_Invoices")',
aoColumnDefs: [
{
aTargets: [0],
"mRender": function (data, type, full) {
NewHotel(full[0]);
return "<input id='btnResp' type='radio' class='open-AddRespDialog btn btn-primary' data-toggle='modal' data-target='#exampleModal1' data-whatever='' data-id=" + data + ">";
}
}],
fnServerParams: function (aoData) {
aoData.push(
{ name: "Trip_No", value: $("#txtTripNo").val() }
);
}
});
My Popup Function :
function NewHotel(i) {
var items = '';
items += "<div class='modal fade' id='exampleModal1"+i+"' tabindex='-1' role='dialog' aria-labelledby='exampleModalLabel'>"+
"<div class='modal-dialog' role='document'>"+
" <div class='modal-content'>"+
" <div class='modal-header'>"+
" <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button>"+
" </div>"+
" <div class='modal-body'>"+
" <form>"+
" <div class='form-group'>"+
" <div class='box-body'>"+
" <div class='row'>"+
" <input name='Item2.HI_Rm_Tariff' class='form-control textDecor abc' type='text' value="+i+"/>"+
" </div>"+
" </div> "+
" </div> "+
" </form>"+
" </div>"+
" </div>"+
" </div>"+
"</div>";
$('#rData').append(items);
items = '';
}
Add a class in Radio-button like '.exampleModal1"+i+"' and Model code add Model property code like this and listen 'i' dynamically from your .net file.
function NewHotel(i) {
var items = '';
items += "<div class='modal fade' id='exampleModal1"+i+"' tabindex='-1' role='dialog' aria-labelledby='exampleModalLabel' data-target='.exampleModal1"+i+"'>"+
"<div class='modal-dialog' role='document'>"+
" <div class='modal-content'>"+
" <div class='modal-header'>"+
" <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button>"+
" </div>"+
" <div class='modal-body'>"+
" <form>"+
" <div class='form-group'>"+
" <div class='box-body'>"+
" <div class='row'>"+
" <input name='Item2.HI_Rm_Tariff' class='form-control textDecor abc' type='text' value="+i+"/>"+
" </div>"+
" </div> "+
" </div> "+
" </form>"+
" </div>"+
" </div>"+
" </div>"+
"</div>";
$('#rData').append(items);
items = '';
}
Related
I am trying to create an additional form text field on click of a button which wotrtks fine, my only problem is that the select option is blank and when I inspect element I see that NAN is added to it.
Here is the design for the dynamic form elements container
<div class="col-sm-6" id="prescription-container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" class="form-control search-select">
<?php echo $drug_drop_down; ?>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Comment</label>
<div class="phone-icon">
<input type="text" class="form-control" name="diagnosis">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<a href="#" id="add_prescription" class="btn btn-warning"><i class="fa fa-plus"></i>Add
prescription</a>
</div>
</div>
This is how I have implemented the onclick listener for the add prescription button
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
var result="<option value=''>Select Drug<option>";
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
if (data.length > 0) {
$.each(data, function(i, item) {
result += "<option value='" + data.id + "'>"+data.name+"<option>";
})
} else{
result += "<option value='" + data.id + "'>"+data.name+"<option>";
}
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ result +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Finally this is the controller sending back data
function () {
$drugs = Medicine::get();
return response()->json( $drugs);
}
Now my problem is that when i alert(data) I get [object Object],[object Object]. This made me modify the controller as follows
function () {
$drugs = Medicine::get();
$drug_drop_down = "<option>Select drug</option>";
foreach($drugs as $drug){
$drug_drop_down .="<option value='".$drug->id."'>$drug->name</option>";
}
return response()->json( $drug_drop_down);
}
and the onclick listener to
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ data +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Now if I alert(data) I get <option>Select drug</option><option value='1'>Quinine</option><option value='2'>Malariaquine</option> but the select is still being added without options and the following appear on inspect element for the added filed
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" '="" class="form-control">NaN</select>
</div>
</div>
</div>
What could I be doing wrong here?
After some searching just realized that the second way was supposed to work except that this + + data + "</select>" + means I am using + as an addition operator and not a concatenator, changing it to + data + "</select>" + solved my problem. I do not still understand what the issue could have been with the first approach
I'm currently working on something to store matches/events in a database. I like to note that this is my first use of jQuery. Everything is pretty much done, expect this problem.
I use PHP to create a list of teams. When a 'team' is selected, the matches of that team are loaded into div "display". Every match has a id, title, date and time field.
<?php
// show_overview.php
$event_info = mysqli_query($conn, "SELECT e.match_id, e.title, e.date, e.starttime
FROM matches AS e
WHERE e.team_id = '$team' AND e.date >= CURDATE()
ORDER BY e.date asc;");
foreach($event_info as $row) {
$events[] = array('match_id' => $row['match_id'], 'title' => stripslashes($row['title']), 'date' => $row['date'], 'starttime' => $row['starttime']);
}
$data['events'] = $events;
echo json_encode($data);
?>
Here we have the body of the page. In the dropdown box you can select your team.
<!-- BEGIN MATCHES -->
<div class="form-group row">
<label for="team-matchlist" class="col-sm-8 col-md-7 col-form-label">Kies van welk team je de wedstrijden wilt zien:</label>
<div class="col-sm-2 col-md-3 mb-5">
<select class="form-control" id="team-matchlist" name="team-matchlist">
<?php
// Create a list of teams to select the matches. This is loaded in the header. The list is correctly showing.
// $teams = mysqli_query($conn,"SELECT * FROM teams ORDER BY team;");
if ($hierarchy_session >= 3):
while($team = mysqli_fetch_assoc($teams)):
echo '<option value="' . $team['team_id'] . '">' . $team['team'] . '</option>';
endwhile;
mysqli_data_seek($teams, 0);
else:
echo '<option value="' . $team_id_session . '">' . $teamname_session . '</option>';
endif;
?>
</select>
</div>
<!-- Here is the match data loaded -->
<div id="display" class="container"></div>
</div>
</div>
<!-- END MATCHES -->
In are the matches loaded. There are two buttons created for editing a match. It won't connect the data to the modal. I can't get my head around it. I think it's a binding problem, but I can't make it to work.
If I use php directly to export the data, it works. But when I load the data in jQuery. It won't load the data in the body of the modal.
I looked at bind, but I couldn't make that work. I hope someone can make me look in the right direction. I tried to make the code as little as possible.
$(document).ready(function() {
// BEGIN SHOW MATCHES
// Create a list of all the matches from database
// When a team is selected
$("#team-matchlist").change(function () {
var team = $(this).val();
$.ajax({
url: "show_overview.php",
type: "POST",
dataType: "json",
data: {
team: team
},
success: function(response) {
var i;
var display = document.getElementById("display");
if (response.events.length > 0) {
display.innerHTML = "";
var user_hierarchy = '<?php echo $hierarchy_session;?>';
var user_team = '<?php echo $team_id_session;?>';
for (i = 0; i<response.events.length; i++) {
display.innerHTML += (
"<form method='post' class='mb-5 text-md-right'>" +
"<div class='form-group row'>" +
"<label for='firstname' class='col-sm-4 col-md-3 col-form-label'>Titel</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='text' class='form-control' id='etitle-" + response.events[i].match_id + "' name='title' value='" + response.events[i].title + "'>" +
"</div>"+
"</div>"+
"<div class='form-group row'>" +
"<label for='lastname' class='col-sm-4 col-md-3 col-form-label'>Datum</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='date' class='form-control' id='edate-" + response.events[i].match_id + "' name='date' value='" + response.events[i].date + "'>" +
"</div>"+
"</div>"+
"<div class='form-group row'>" +
"<label for='lastname' class='col-sm-4 col-md-3 col-form-label'>Starttijd</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='time' class='form-control' id='estarttime-" + response.events[i].match_id + "' name='starttime' value='" + response.events[i].starttime + "'>" +
"</div>"+
"</div>"+
// Here is the button for editing the match
"<div class='form-group btn-group'>"+
"<button type='button' id='edit_match-" + response.events[i].match_id + "' class='btn btn-primary edit-match' data-toggle='modal' data-target='#modal-edit_match'>" +
"Wijzigen" +
"</button>" +
"</div>"+
"<hr/>"+
"</form>"
);
}
} else {
display.innerHTML = "Er zijn geen wedstrijden voor dit team.";
}
}
});
}).change();
// Show info for confirmation in modal
$('.edit-match').on("click", function() {
var itemID = $(this).attr("id");
var split = itemID.split("-");
var id = split[1];
var title = $("#etitle-"+id).val();
var date = $("#edate-"+id).val();
var starttime = $("#estarttime-"+id).val();
var elem_id = document.getElementById("edit_match");
var title_id = document.getElementById("modal-title-edit_match");
var body_id = document.getElementById("modal-body-edit_match");
var date = new Date(date + "T" + starttime);
const date_options = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'};
const time_options = { hour: 'numeric', minute: 'numeric' };
var datestring = date.toLocaleDateString('nl-NL', date_options);
var timestring = date.toLocaleTimeString('nl-NL', time_options);
title_id.innerHTML = "Wedstrijd wijzigen";
body_id.innerHTML = "Titel: " + title +
"<br>Datum: " + datestring +
"<br>Starttijd: " + timestring +
"<br><br>Weet u zeker dat u deze wedstrijd wilt wijzigen?";
$(".edit_match").attr("id", "edit_match-" + id);
});
});
</script>
The confirmation is not applied in the modal.
Below we have the modal. The modal is loaded. Only the javascript is not applied to the modal. It remains empty.
<!-- BEGIN MODALS -->
<!-- Modal after clicking on edit match -->
<div class="modal fade" id="modal-edit_match" tabindex="-1" role="dialog" aria-labelledby="modal-title" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-title-edit_match">Wedstrijd wijzigen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Sluiten">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body-edit_match">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuleren</button>
<button type="button" name="edit_match" id="edit_match" class="btn btn-primary edit_match">Wijzigen</button>
</div>
</div>
</div>
</div>
<!-- END MODALS -->
Does anyone have any ideas?
So basically what I am trying to achieve is allowing the user to be able to add to an existing set of information that will be passed on to Vue from JSON.
So the following code is my HTML code which comprises of the div element with the id objectiveArea that vue will render to and a hard coded button for the users to add more entries.
<div class="form-group" id="objectiveArea"></div>
<div><input type="button" value="Add Objective" id="addButton" /></div>
And here is my Javascript where I pass the JSON into vue for it to render as well as having an onclick event when the add button is triggered. The function addNewObjectiveRow serves as a template to append when the user clicks add and the objectiveElements is a template for vue to render the existing JSON to the HTML.
function addNewObjectiveRow(value) {
var $divElements = "<div class='row'>"
+ "<div class='form-inline'>"
+ "<br /><div class='form-group'><label class='control-label'>Title</label><div class=''><input type='text' class='form-control objectivetitle' placeholder='Title' /></div></div>"
+ " "
+ "<div class='form-group input-group'><label class='control-label'>Target Completion Date</label><div class=''><input readonly type='text' class='form-control targetdateinput' placeholder='Select Date' /><span class='input-group-addon'><i class='glyphicon glyphicon-calendar'></i></span></div></div>"
+ " "
+ "<div class='form-group'><label class='control-label'></label><div><input type='button' value='Remove Goal' class='btn-remove btn-danger deleteButton' /></div></div>"
+ "</div>"
+ "<br />"
+ "<div class='form-group'><label class='control-label'> Details</label><div><textarea class='form-control text-area-width goaldetails' rows='4' placeholder='Enter details here...'></textarea></div></div><hr />"
+ "</div>"
return $divElements;
}
var objectiveElements = "<div class='row'><div v-for='(objective, index) in objectivesData'>"
+ "<div class='form-inline'>"
+ "<br /><div class='form-group'><label class='control-label'>Title</label><div class=''><input type='text' class='form-control objectivetitle' placeholder='Title' v-model='decodeData(objective.Title)' /></div></div>"
+ " "
+ "<div class='form-group input-group'><label class='control-label'>Target Completion Date</label><div class=''><input readonly type='text' class='form-control targetdateinput' placeholder='Select Date' v-formatdate='objective.TargetDate' /><span class='input-group-addon'><i class='glyphicon glyphicon-calendar'></i></span></div></div>"
+ " "
+ "<div class='form-group'><label class='control-label'></label><div><input type='button' v-if='(index > 0)' value='Remove Goal' class='btn-remove btn-danger deleteButton' /></div></div>"
+ "</div>"
+ "<br />"
+ "<div class='form-group'><label class='control-label'> Details</label><div><textarea class='form-control text-area-width goaldetails' rows='4' placeholder='Enter details here...' v-model='decodeData(objective.Details)'></textarea></div></div><hr />"
+ "</div></div>";
var data = JSON.parse('[{"Title":"Title One","TargetDate":"21 June 2017","Details":"Details One"},{"Title":"Title Two","TargetDate":"22 June 2017","Details":"Details Two"}]');
var Objectives = Vue.extend({
template: objectiveElements,
data: function () {
return {
objectivesData: data
}
}
})
new Objectives().$mount('#objectiveArea');
$('#addButton').on('click', function () {
$('#objectiveArea').append(addNewObjectiveRow(""));
});//end addButton on click
However, the above code renders the existing information from the JSON just fine in the HTML but when I click on the add button, nothing happens at all. Am I missing something or getting it all wrong?
https://v2.vuejs.org/v2/guide/list.html
HTML
<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
<button #click="addItem()">Add new item</button>
JS
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
},
methods: {
addItem(){
this.items.push({message: 'new message'})
}
}
})
Clicking the button will execute addItem() method which will add a new item into data items and it will automatically render new li
there are many mistakes
the function addNewObjectiveRow(value)you don't use the parameter value.
Vue is data-driven, you should change the objectivesData, not simply append the string. Read the document
I have an app with 3 buttons, the 3 buttons make an AJAX call to retrieve some data and redraw a table with the data. However when clicked the button should be kept highlighted so the user knows which data they are viewing.
This is the JS code that calls the Web API method:
iniciativasEstrategicas.GetVistaActividades = function (filtro) {
var idObjetivoValue = sessionStorage.idObjetivoValue;
$('#tab_vista1').html('<br><br><br><img class="loadImage" src="Images/loader.gif" />');
$.ajax({
url: 'IniciativasEstrategicasWebPart/GetVistaActividades',
type: 'POST',
data: {
idObjetivo: idObjetivoValue,
filtro: filtro
},
success: function (data) {
drawVistaActividades(data);
},
error: function (data) {
showErrorMessage(data);
}
});
}
This is the method that draws the data:
function drawVistaActividades(data) {
resetBreadCrumb();
var html = "";
for (var i = 0; i < data.length; i++) {
html += template.rowVistaActividades
.replace("{0}", data[i].nombreActividad)
.replace("{1}", data[i].iniciativaName)
.replace("{2}", data[i].fechaVencimiento)
.replace("{3}", data[i].fechaRealTerminacion)
.replace("{4}", data[i].responsables);
}
$("#tab_vistaActividades").html("<br>" + "<br>" + template.tableVistaActividades.replace("{0}", html));
}
This is the table template that I use to draw the data, and the buttons are there
tableVistaActividades: "<div>" +
"<div>" +
"<div class=\"btn-group\" role=\"group\" aria-label=\"Basic example\">" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('A tiempo')\">A tiempo</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Atrasadas')\">Atrasadas</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Pendientes')\">Pendientes</button>" +
"</div>" +
"</div>" +
"<table class='table'>" +
"<thead>" +
"<tr>" +
"<th>" +
"Actividad" +
"</th>" +
"<th>" +
"Iniciativa" +
"</th>" +
"<th>" +
"Fecha propuesta" +
"</th>" +
"<th>" +
"Fecha real terminación" +
"</th>" +
"<th>" +
"Responsables" +
"</th>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"{0}" +
"</tbody>" +
"</table>" +"<div>",
and the row template
rowVistaActividades: "<tr>" +
"<td>" +
"{0}" +
"</td>" +
"<td>" +
"{1}" +
"</td>" +
"<td>" +
"{2}" +
"</td>" +
"<td>" +
"{3}" +
"</td>" +
"<td>" +
"{4}" +
"</td>" +
"</tr>",
As you can see in this page.
We are using the same Bootstrap button code and in that page the button remains highlighted when clicked.
This should solve your problem, basically you need to add "active" to selected option and remove "active" from siblings which was previously selected.
$(".btn-group > .btn").click(function(){
$(this).addClass("active").siblings().removeClass("active");
$(this).addClass("active");
});
As #taTrifynor said in the comment, you should simply use Button groups with input type="radio", read about it. For example:
JSFiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked="checked"/>Button 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"/>Button 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"/>Button 3
</label>
</div>
Or I don't understand what do you want.
I have this
<div id="inprog_table">
</div>
I tried this to insert
var div = document.getElementById('inprog_table');
div.innerHTML = div.innerHTML+
"<div class='row'>
<div class='col-xs-7'>
"+ $(".row.active .col-xs-7 p:first-child").text()+"
</div>
<div class='col-xs-2'>
"+ $(".row.active .col-xs-7 p:last-child").text()+"
</div>
<div class='col-xs-2'>
1
</div>"
inside inprog_table div. I know it's really wrong, but I don't know how to append all of this.
String literals in JavaScript cannot extend through multiple lines, you'll have to make each string end on the same tine it started or escape the new line with a \
var div = $('#inprog_table');
div.append( "<div class='row'>"+
"<div class='col-xs-7'>"+
$(".row.active .col-xs-7 p:first-child").text() +
"</div>" +
"<div class='col-xs-2'>" +
$(".row.active .col-xs-7 p:last-child").text()+
"</div>"+
"<div class='col-xs-2'>1</div>"+
"</div>");
Use jQuery for this stuff. Pure Javascript is just too much of a hassle.
Here's the code in jQuery:
$('#inprog_table').html(
'<div class="row">' +
'<div class="col-xs-7">' +
$(".row.active .col-xs-7 p:first-child").text() +
'</div>' +
'<div class="col-xs-2">' +
$(".row.active .col-xs-7 p:last-child").text() +
'</div>' +
'<div class="col-xs-2">1</div>' +
'</div>'
);
Use .append()
$('#inprog_table').append("<div class='row'><div class='col-xs-7'>" + $(".row.active .col-xs-7 p:first-child").text() + "</div><div class='col-xs-2'>" + $(".row.active .col-xs-7 p:last-child").text() + "</div><div class='col-xs-2'>1</div>");
Use .html()
$('#inprog_table').html(function (_, old_html) {
return old_html + "<div class='row'><div class='col-xs-7'>" + $(".row.active .col-xs-7 p:first-child").text() + "</div><div class='col-xs-2'>" + $(".row.active .col-xs-7 p:last-child").text() + "</div><div class='col-xs-2'>1</div>"
});
You can either use:
.append()-
Ex: $("#div1").append(Element to append)
Or
.after()-
Ex: $("#div1").after(Element to append)