how to pass value from a boostrap modal child to parent? - javascript

I been trying to pass any value from my window modal child to the parent window, but it doesn't work. The modal doesn't hide or send the value to the parent window when I click Save.
application.php
<body>
<h3 class="h3 black">Application</h3>
<form class="form-horizontal" method="post" action="admin-controller.php" name="f1">
<input type="text" name="p_name" id="n1" >
<?php
include 'includes/calendar.php';
$calendar = new Calendar();
echo $calendar->show();
?>
</form>
</body>
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0 /jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript">
function post_value(){
window.opener.document.f1.p_name = document.myform.skill_id_t.value;
$('#modal_1').modal('hide');
}
</script>
calendar.php
<?php
class Calendar {
public function show() {
//some code
$html .=$this->_showDay($someValues);
//some code
}
private function _showDay($cellNumber){
// Build up the html.
$html = '<td id="' . $this->currentDate . '" class="td-top-text ' . $classNameOne . $classNameTwo . '">';
//Radio button that open the Modal window
$html .= '<input type="radio" data-toggle="modal" data-target="#modal_1" name="schedule_id" value="'. $shedule_id.'">';
//singleModal
$html .=$this->_singleModal();
$html .= '</td>';
return $html;
}
//child window
public function _singleModal(){
//Single Modal
$html = '<form name="myform" method="post" action="">';
$html .= '<div class="modal fade" id="modal_1" role="dialog">';//Modal open
$html .= '<div class="modal-dialog">';//Modal Dialog open
$html .= '<div class="modal-content">';//Modal-Content Open
$html .= '<div class="modal-header">';//Modal-Header open
$html .= '<button type="button" class="close" data-dismiss="modal">×</button>';//bbutton
$html .= '<h4 class="modal-title bold cyan">Sign Up (Single)</h4>';//Title H4
$html .= ' </div>';//Modal-header Close
$html .= '<div class="modal-body">';//Modal-body open
//Type something to pass to parent window
$html .= '<input name="skill_id_t" type="text">';
$html .= '</div>';//Modal-body close
$html .= '<div class="modal-footer">';//Footer open
$html .= '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';//button
$html .= '<input onclick="post_value();" id="save" type="button" name="save-details" value="Save">';//input
$html .= '</div>';//Footer Close
$html .= '</div>';//Modal-content close
$html .= '</div>';//Modal Dialog Close
$html .= '</div>';//Modal close
$html .= '</form>';
return $html;
}
}
I read other posts and according to them, the problem could be javascript because I cant use data-target="#modal_1" with javascript so I tried to delete the target and just add onclick call a function into my <input name="schedule_id"> to do $(#modal_1).modal('show'); but still the $(#modal_1).modal('hide'); doesn't work.
I also had tag php because according to other posts, I need to include the javascript into my php (calendar.php) and not in my application.php
Edit
I also got some error every time I click on Save
TypeError: opener is null
Tried to fix it by adding window.opener... but it didn't work either
New Edit:
I have change my js code to this:
$(function() {
$('#btnLaunch_1').click(function() {
$('#modal_1').modal('show');
});
$('#btnSave_1').click(function() {
opener.document.f1.p_name = document.myform.skill_id_t.value;
$('#modal_1').modal('hide');
});
$('#cancel_1').click(function() {
$('#modal_1').modal('hide');
});
});
and I remove everything that have to be with data-target including the one that close the window data-dismiss. And, I realized that the problem is this line opener.document.f1.p_name = document.myform.skill_id_t.value; for some reason this line fail by giving the above error. ...opener is null
Pleaseeee helpp =/ II am trying hard here....

So, after googling more and more and follow some suggestions from the first comment, I believe that the best way to get the values from a bootstrap modal child window and add it to the parent window is by using jQuery in this way:
$(function() {
//open modal
$('#btnLaunch_1').click(function() {
$('#modal_1').modal('show');//no need data-target just <input id="">
});
$('#btnSave_1').click(function() {
//Get the value from the child into a variable
value = $('[name="skill_id_1"]').val();
//Set the value to the parent window
$('[name="p_name"]').val(value);
//make the modal dismiss (no need data-target)
$('#modal_1').modal('hide');
});
//if user click cancel instead of use data-dismiss, just hide it
$('#cancel_1').click(function() {
$('#modal_1').modal('hide');
});
});
If you find a better solution that this one, please let me know
Thanks

Your opener form name is wrong;
Change
window.opener.document.f1.p_name to
window.opener.document.myform.p_name
as you refer
<form name="myform" method="post" action="">

Related

i get same id in array

I have recursive menu function from DB.
I add some jquery codes to it.
I click plus symbol then i can see all parent nodes.
I will add: add edit delete record buttons to popover later.
I created click function to fa fa-cog, but it is always show to same id on alert.
I try from 2 days but i can not display correct clicked id in the jquery script codes.
i wanna display correct id in popover <a href="<?php echo $Linkid ;?>"</a> window. Thanks.
<?php
// Select all entries from the menu table
$result=mysqli_query($baglan, "SELECT * FROM posts ORDER BY sira ASC");
// Create a multidimensional array to conatin a list of items and parents
$menu = array(
'items' => array(),
'parents' => array()
);
// Builds the array lists with data from the menu table
while ($items = mysqli_fetch_assoc($result))
{
// Creates entry into items array with current menu item id ie. $menu['items'][1]
$menu['items'][$items['id']] = $items;
// Creates entry into parents array. Parents array contains a list of all items with children
$menu['parents'][$items['kat_id']][] = $items['id'];
}
// Menu builder function, parentId 0 is the root
function buildMenu($parent, $menu)
{
$html = "";
$buton = '<a class="buton"><button class="btn btn-default btn-xs"><i class="fa fa-plus"></i></button> </a>';
if (isset($menu['parents'][$parent])){
$html .= "<ul>";
$html .= '<div class="left" id="nav">';
foreach ($menu['parents'][$parent] as $itemId){
if(!isset($menu['parents'][$itemId])){
$Linkid = $menu['items'][$itemId]['id'];
$ayarbuton = '<a class="goster" id="'.$Linkid.'" href="#" data-toggle="tooltip" title="'.$Linkid.'"><button class="btn btn-danger btn-xs"><i class="fa fa-cog"></i></button> </a>';
$html .="<div class='editRecord'";
$html .= "<li>".$ayarbuton.$menu['items'][$itemId]['isim'].$menu['items'][$itemId]['id']."</li>";
$html .="</div>";
}
if(isset($menu['parents'][$itemId])){
$Linkid = $menu['items'][$itemId]['id'];
$html .= "<div class='bs-example'><div id='myTooltips'>";
$ayarbuton = '<a class="goster" id="'.$Linkid.'" href="#" data-toggle="tooltip" title="'.$Linkid.'"><button class="btn btn-danger btn-xs"><i class="fa fa-cog"></i></button> </a>';
$html .= "<li>".$buton.$ayarbuton . $menu['items'][$itemId]['isim']." ID = " .$Linkid;
$html .= buildMenu( $itemId, $menu );
$html .= "</div></div></li>";
}
}
$html .= '</div>';
$html .= "</ul>";
}
return $html;
}
echo buildMenu(0, $menu);
global $Linkid;
?>
<script type="text/javascript">
$(document).ready(function(){
$(".goster").click(function(){
var linkID = $(".goster").attr("id");
alert(linkID);
$("#myTooltips a").tooltip({
template : '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-head"><h3><span class="glyphicon glyphicon-info-sign"></span> <?php echo $Linkid ;?></h3></div><div class="tooltip-inner"></div></div>'
});
});
});
</script>
<script>
$('#nav .buton').css({cursor: "pointer"}).on('click', function(){
var txt = $(this).html() == '<button class="btn btn-default btn-xs"><i class="fa fa-plus"></i></button> '?'<button class="btn btn-default btn-xs"><i class="fa fa-minus"></i></button> ':'<button class="btn btn-default btn-xs"><i class="fa fa-plus"></i></button> ';
$(this).html(txt);
$(this).nextAll('ul').eq(0).slideToggle('fast');
})
</script>
With ".goster" selector you are selecting all the elements having goster class but no way of determine which one was actually clicked.
In order to get the specific clicked element, you can use this in the click callback. Try change your handler to
$(".goster").click(function(e){
var linkID = this.id;
alert(linkID);
});
finaly i will do it,
thanks all.
<script type="text/javascript">
$(document).ready(function(){
$(".goster").click(function(e){
var linkID = e.currentTarget.id; // e.target is the clicked element
$(".goster").attr("href", linkID); // this will change the link URL
});
$("#myTooltips a").tooltip({
template : '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-head"><h3><span class="glyphicon glyphicon-info-sign"></span> TOOLTIP</h3></div><div class="tooltip-inner"></div></div>'
});
});
</script>

How to post/send form fields return by ajax to the server using jQuery $.post

Good day fellows, I'm displaying a form via ajax based on some drop downs menus. User can can select the class on one dropdown and subject on another, which in turn returns a list of students in that class.
This is formated in a form like manner that allows user to enter scores of subjects that a student have acquire. This is how the form looks after user have selected their preferences:
I want when the save button is click and after user have enter the score, it should be send to the database. I'm facing few problems:
When the score field is empty(since I added a required attribute) it doesn't validate that the field is empty, but rather send a request to the file that is responsible to insert records.
When the request reaches the file responsible to insert records(create_score.php) it's like no values were send through the form. I know this because I var_dump($_POST) and it return this array(0) { }
This is the script I'm using to return the file:
$(document).ready(function() {
$('#subject_id').on('change', function(){
var subject_id = $('#subject_id').val();
var class_id = $('#class_id').val();
var term = $('#term').val();
if (subject_id != '' || class_id != '') {
$.ajax({
url:"includes/ajax/read_student_score_form.php",
method:"post",
data:{"subject":subject_id, "class":class_id, "term":term},
dataType:"text",
success:function(data){
$("#result").html(data);
}
});
} else {
$("#result").html('');
}
});
$('#class_id').on('change', function(){
var subject_id = $('#subject_id').val();
var class_id = $('#class_id').val();
var term = $('#term').val();
if (subject_id != '' || class_id != '') {
$.ajax({
url:"includes/ajax/read_student_score_form.php",
method:"post",
data:{"subject":subject_id, "class":class_id, "term":term},
dataType:"text",
success:function(data){
$("#result").html(data);
}
});
} else {
$("#result").html('');
}
});
$('#term').on('change', function() {
/* Act on the event */
var subject_id = $('#subject_id').val();
var class_id = $('#class_id').val();
var term = $('#term').val();
if (subject_id != '' || class_id != '') {
$.ajax({
url:"includes/ajax/read_student_score_form.php",
method:"post",
data:{"subject":subject_id, "class":class_id, "term":term},
dataType:"text",
success:function(data){
$("#result").html(data);
}
});
} else {
$("#result").html('');
}
});
When the submit is click the is how I structure my code to post values to file responsible to insert records(create_score.php)
$(document).on('click', '#savebtn', function(event) {
event.preventDefault();
// this is where I'm testing if the button is working
alert("Button click");
console.log("Button click for console");
var form = $('#st_score_form');
var formdata = form.serialize();
$.post("includes/ajax/create_score.php", formdata)
.done(function(data){
$("#success").fadeIn('slow', function(){
$("#success").html('<div class="alert alert-info alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-check"></i>Alert! </b>'+data+'</div>');
});
})
.fail(function(data){
$("#success").fadeIn('slow', function(){
$("#success").html('<div class="alert alert-warning alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-warning"></i>Alert! </b>'+data+'</div>');
});
});
});
$('body').append('<button id="#savebtn"></button>');
This is how I'm returning the form(read_student_score_form.php):
if (mysqli_num_rows($result) > 0) {
# code...
$output .= '<h4 align="center">Periodic Report</h4>';
$output .= '<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th scope="row" colspan="1">Subject</th>
<td colspan="5">'.$subject["subject_name"].'</td>
<th scope="row">Class</th>
<td>'.$class['class_name'].'</td>
<th scope="row">Period</th>
<td>'.$period.'</td>
</tr>';
$output .= '</table>';
$output .= '<table class="table table-bordered table-condensed table-responsive table-striped">
<thead>
<tr>
<th>Student</th>
<th>Score</th>
<th>Operations</th>
</tr>
</thead>';
$output .= '<tbody>';
while ($row = mysqli_fetch_array($result)) {
# code...
$output .= '<form action="#" method="post" id="st_score_form">';
// unseen fields values that will be send
$output .= '<tr style="display: none;">';
$output .= '<td><input type="text" name="student_id" value="'.$row['student_id'].'"></td>';
$output .= '<td><input type="text" name="subject_id" value="'.$subject_id.'"></td>';
$output .= '<td><input type="text" name="class_id" value="'.$class_id.'"></td>';
$output .= '<td><input type="text" name="term" value="'.$term.'"></td>';
$output .= '</tr>';
// -- end of unseen fields
$output .= '<tr>';
$output .= '<td>'.$row["first_name"]." ".substr($row["middle_name"], 0, 1).". ".$row["surname"].'</td>';
$output .= '<div class="form-group">';
$output .= '<td><input type="number" min="59" max="100" name="score" class="form-control" required="required"></td>';
$output .= '<td><input type="submit" name="savebtn" id="savebtn" value="Save" class="btn btn-info form-control"></td>';
$output .= '</div>';
$output .= '</tr>';
$output .= '</form>';
}
$output .= '</tbody>';
$output .= '</table>';
$output .= '</div>';
echo $output;
} else {
echo "Data not found";
}
Contents of file responsible to insert records (create_score.php)
if (isset($_POST)){
// just testing to see values posted
echo var_dump($_POST);
}
I'm open to feed backs and suggestions on ways I can make this work. Thanks!!!
UPDATE This is how I'm now displaying my form
$output .= '<form action="#" method="post" id="st_score_form">';
while ($row = mysqli_fetch_array($result)) {
# code...
// unseen fields values that will be send
$output .= '<tr style="display: none;">';
$output .= '<td><input type="text" id="student_id" name="student_id" value="'.$row['student_id'].'"></td>';
$output .= '<td><input type="text" name="subject_id" value="'.$subject_id.'"></td>';
$output .= '<td><input type="text" name="class_id" value="'.$class_id.'"></td>';
$output .= '<td><input type="text" name="term" value="'.$term.'"></td>';
$output .= '</tr>';
// -- end of unseen fields
$output .= '<tr>';
$output .= '<td>'.$row["first_name"]." ".substr($row["middle_name"], 0, 1).". ".$row["surname"].'</td>';
$output .= '<div class="form-group">';
$output .= '<td><input type="number" min="59" max="100" name="score" class="form-control" required="required"></td>';
$output .= '<td><input type="submit" name="savebtn" id="savebtn" value="Save" class="btn btn-info form-control"></td>';
$output .= '</div>';
$output .= '</tr>';
}
$output .= '</form>';
you have multiple elements with same ID, specificaly
id="savebtn"
first one is appended with jQuery, and second one comes over wire and you try to add that one too.. that can be a messy,, try to isolate or change the button refs, or classes,, try to switch to classes and ditch ID's once and for all, I did that long time ago and my life changed for the better :)
also,, for your issue number
1) try to add check same way you have for other event
$(document).on('click', '#savebtn', function(event) {
event.preventDefault();
var form = $('#st_score_form');
var formdata = form.serialize();
// check for value if not empty
var subject_id = $('#subject_id').val();
var class_id = $('#class_id').val();
var term = $('#term').val();
if (subject_id != '' || class_id != '') {
$.post("includes/ajax/create_score.php", formdata)
.done(function(data){
$("#success").fadeIn('slow', function(){
$("#success").html('<div class="alert alert-info alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-check"></i>Alert! </b>'+data+'</div>');
});
})
.fail(function(data){
$("#success").fadeIn('slow', function(){
$("#success").html('<div class="alert alert-warning alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="glyphicon glyphicon-remove-circle"></i></button><b><i class="fa fa-warning"></i>Alert! </b>'+data+'</div>');
});
});
}
});
for your issue number
2) when you get results from read_student_score_form.php page try to run this in your browser console to see if you have any results,,, that's before you try to send it to server,,
var form = $('#st_score_form');
var formdata = form.serialize();
run that, and get me your results here so maybe we can continue on this issue,,
UPDATE:
you are loop wrongly... take a look on your while in php and that one would render multiple <form action="#" method="post" id="st_score_form"> and that's wrong.. move it before while,, something like this:
<?php
$output .= '<form action="#" method="post" id="st_score_form">';
while ($row = mysqli_fetch_array($result)) {
} // end while
$output .= '</form>';

How to use javascript to activate the button when checkbox is checked?

I need for this php file a modification but I don't know javascript. This makes it really hard for me how to do it.
I want to do this:
If checkbox is checked than activate my submit button else don't activate them (default).
I already did some modifications:
I added the checkbox with id= checkbox and I added the parameter disabled="disabled" to my button.
This is working. Now I need only to activate the button when checkbox is checked.
But I have now 2 problems:
I don't know where to put the javascript code to my file
I don't know to I can call or activate javascript in my code
Would be really nice if someone could help me.
<?php
if(isset($_POST['photo-name'])){
$photo_name = $_POST['photo-name'];
}
if(isset($_POST['photo-title'])){
$photo_title = $_POST['photo-title'];
}
if(isset($_POST['photo-description'])){
$photo_description = $_POST['photo-description'];
}
if(empty($photo_name)){
$photo_name = '';
}
if(empty($photo_description)){
$photo_description = '';
}
$sql= $wpdb->get_results("SELECT name,id FROM ".$wpdb->prefix."u_gallery_cat ORDER BY name ASC");
$html .= '<div><label for="photo-name"><strong>'.__('Caption:','user-gallery').'</strong></label></div>';
$html .= '<div class="contest-input"><input type="text" name="photo-name" id="photo-name" value="'.$photo_name.'" /></div>';
$html .= '<div><label for="photo-content"><strong>'.__('Description:','user-gallery').'</strong> <span class="contest-small-font-2">'.__('(Optional)','user-gallery').'</span></label></div>';
$html .= '<div class="contest-input"><textarea class="photo-description-textarea" name="photo-description" id="photo-description">'.$photo_description.'</textarea></div>';
if(!empty($sql)){
$html .= '<div><label for="photo-category"><strong>'.__('Category:','user-gallery').'</strong></label></div>';
$html .= '<select name="photo-category" id="photo-category">';
foreach($sql as $item){
$html .= '<option value="'.$item->id.'">'.$item->name.'</option>';
}
$html .= '</select>';
}
if ($photo_limit == 100000000){
$html .= '<div><label for="user-photo"><strong>'.__('Select image:','user-gallery').'</strong></label></div>';
}else{
$html .= '<div><label for="user-photo"><strong>'.__('Select image: (max.','user-gallery').' '.$p_limit.')</strong></label></div>';
}
$html .= '<div class="contest-input"><input type="file" name="user-photo" id="user-photo" size="50" accept="image/*" onchange="loadFileU(event)" class="selimg"></div>';
$html .= '<img id="coutput"/>';
$html .= '<div class="ug-clear"></div>';
$html .= '<input type="hidden" name="user_id" />';
$html .= '<input type="hidden" name="action" value="new_post" />';
$html .= '<div class="contest-button-div">';
$html .= '<div class="contest-button"><input type="checkbox" name="chk" id="chk" value="yourvalue" class="checkbox"></div>';
$html .= '<div class="contest-button"><input type="submit" value="'.__('Add Photo','user-gallery').'" id="submit" disabled="disabled" name="submit" class="ug-styled-button tooglebutton" /></div>';
$html .= '<div class="ug-clear"></div>';
$html .= '</div>';
$html .= '<div class="ug-clear"></div>';
$html .= '</form>';
$html .= '<div class="ug-clear"></div>';
$html .= '</div>';
}
?>
Without using Jquery :
On your checkbox add a onchange() event to trigger Javascript:
<div class="contest-button"><input type="checkbox" name="chk" id="chk" value="yourvalue" class="checkbox" onchange="openSubmit()"></div>
Then for your script :
<script type="text/javascript">
function openSubmit(){ // This function is called by the checkbox click
if(document.getElementById('chk').checked == true){ // If it is checked
document.getElementById('submit').disabled = false; // Then we remove the disable attribute
}
</script>
Using Jquery :
$('#chk').change(function(){ // You put an event on your checkbox here
if($(this).is(':checked')){ // If statut of checkbox is checked
document.getElementById('submit').disabled = false; // Then we remove the disable attribute
}
});
You can put this script at the bottom of your file after your PHP.

Can the JS Prepend statement edit pre-defined html?

I define my html by setting it equal to a variable i am echoing, just for the sake of keeping my php page dynamic, however i am trying to append another input div onto my text area once a button is clicked via a javascript statement. In terms of syntax i cant seem to find any errors, is this just not allowed?
this is the code for my comment area,
$comment_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" onfocus="showBtnDiv()" placeholder="What's new with you '.$u.'?"></textarea>';
$comment_ui .= '<div id="uploadDisplay_SP"></div>';
$comment_ui .= '<div id="btns_SP" class="hiddenStuff">';
$comment_ui .= '<form action=""><input id="gendercheck" type="checkbox" name="male" onclick="gendertoggle()">male</form>';
$comment_ui .= '<img src="images/topic.JPG" id="triggerTopic" class="triggerBtn" onclick="showtitleDiv" width="137" height="22" title="Add a title" />';
$comment_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'c\',\''.$u.'\',\'statustext\',\''.$male.'\',\'title\')">Post</button>';
$comment_ui .= '<img src="images/camera.JPG" id="triggerBtn_SP" class="triggerBtn" onclick="triggerUpload(event, \'fu_SP\')" width="137" height="22" title="Upload A Photo" />';
$status_ui .= '</div>';
notice i included an image icon for adding a topic to a comment that on click calls this function
function showtitleDiv(){
_("statustext").prepend('<input id="title" onkeyup="statusMax(this,30)" placeholder="Topic headline..."><br />');
/*_("triggerTopic").style.display = "block";*/
}
and i echo the $comment_ui in the body of my document, everything shows, and the comments work, its just the showtitleDiv function isnt working
the javascipt console doesnt show any errors, is the syntax wrong? I appreciate any and all of your expertise!

JQuery/javascript doubleclick=do something on each div from foreach() php

I have this PHP file:
foreach($allfiles as $file) {
echo '<div class="file" id="file' . $file->id . '">';
echo '<div id="checkbox"><img src="images/delete.png" width="15" height="15"></img></div>';
echo '<div id="filename">'. $file->name . '</div>';
echo '<div id="size">| '. $file->size . ' </div>';
echo '<div id="created">'. $file->created . '</div>';
echo '<div id="download"><img src="images/download.png" width="18" height="18"></img></div>';
echo '</div>';
?>
<script>
var id = <?php echo $file->id; ?>
</script>
<?php
}
and this JS file
$('#file' + id).dblclick(function() {
alert(1);
});
What I'm trying to do is that when div "file" + the file id is clicked, it will alert "1" (or open the file).
The problem is that now it only alerts 1 when I doubleclick the last div I have, while it is supposed to be done on all of them.
Is there a solution like foreach div called file + something do ? when doubleclicked.
Sorry if this was very unclear :D
You can use data-* prefixed custom attribute like
echo '<div class="file" data-id="' . $file->id . '">';
Bind your event using the common class and then fetch data-idusing .data()
$('.file').on('dblclick', function() {
alert($(this).data('id'));
});

Categories