I have some data being created(generated from database) using a while loop. Each set of data carries some form of id and its corresponding button is added to it. Now, when I click a button, I'd like to pass the id(single php variable) of the data related to this button to a modal window(that has a form) that pops and also make it the value of an input field. Here's my code so far:
The data from database:
<?php while ($data = mysqli_fetch_assoc($data_set)) { ?>
<div class="w3-section w3-row w3-card-2">
<div class="w3-half">
<div class="apartment-image w3-card-4">
<header class="w3-container">
<h4><?php echo $data['data_name']; ?></h4>
</header>
<div class="w3-container">
<img src="<?php echo "images/".$data['Image1']; ?>" class="w3-image" alt="<?php echo $data['dataimgname']; ?>">
</div>
<footer class="w3-contanier w3-border-top">
<div class="w3-border-right">
<button class="w3-btn w3-btn-block" type="button" name="btnBook" id="modalOpener" onclick="document.getElementById('book').style.display='block';">
Book or Request Tour
</button>
</div>
The Modal:
<div id="book" class="w3-modal">
<div class="w3-modal-content">
<header class="w3-container">
<span onclick="document.getElementById('book').style.display='none'" class="w3-closebtn">
×
</span>
<h2>Book or Request Tour</h2>
</header>
<div class="w3-container">
<form class="w3-form" action="bookntour-handler.php" method="post">
<div class="w3-group">
<label class="w3-label" for="fullname">Full Name:</label>
<input class="w3-input" type="text" name="fullname" value="">
</div>
<label class="w3-label" for="email">E-mail:</label>
<input class="w3-input" type="email" name="email" value="">
<label class="w3-label" for="telephone">Telephone:</label>
<input class="w3-input" type="text" name="telephone" value="">
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
<div class="w3-group">
<input class="w3-btn" type="submit" name="btnSubmit" value="Submit">
</div>
</form>
</div>
<footer>
</footer>
</div>
Like I said earlier, I want to pass the id associated with the button but from my code there is nothing that mentions about "id" so let's use.
<?php echo $data["data_name"]; ?>
When I open the modal window, I'd like this variable to be made as the value for input:
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
I have looked at a couple of options so far but most of them seem unnecessary in my case or I simply don't understand them. Like this and this and this. This seems like a workable solution but it requires me to fetch the whole data again, from the database(using AJAX) which I do not want. I just want that one value.
I am using W3CSS for my layouts and creating the modal. A solution in jQuery/JavaScript or PHP(or both) will be appreciated. Thank you!
Update
So, I somehow managed to solve part of the problem. I added this function to my external JavaScript file:
function showModal() {
document.forms["bookntourForm"]["apartmentno"].value = document.getElementsByClassName("modalOpener")[0].getAttribute("value");
document.getElementById('book').style.display='block';
}
Then the code for the button that calls the above function looks like this:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal()" value="<?php echo $data['data_name']; ?>">
Book or Request Tour
</button>
This brings up a new problem. Whenever I open the modal, the value for <input class="w3-input" type="text" name="dataname" value=""> on the modal is the same for all modals although they are different when each button is generated.
You can pass your id through ajax to the backend and retrieve necessary data regarding that ID by using a query,
Then set values to the necessary place inside the success method.
As you say, I don't think as a good suggestion to use data_name instead of id.
you can set your id in hidden field and use it. because "data_name" will not be good solution to retrieve data by unique field.
I don't know if I have done this in a proper manner, but it was as simple as this. I changed the value of onclick attribute of the button to:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal('<?php echo $apartment["ApartmentNo"]; ?>')">
Book or Request Tour
</button>
The showModal() function in the external JS now looks like this:
var aptNo;
function showModal(aptNo) {
document.forms["bookntourForm"]["apartmentno"].value = aptNo;
document.getElementById('book').style.display='block';
}
It now works the way I wanted.
Related
I've got a form, with 2 buttons
<button>Cancel changes</button>
<button type="submit">Submit</button>
I use jQuery UI's button on them too, simply like this
$('button').button();
However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.
Obviously I could do this
$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).
The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form.
<button type="button">Submit</button>
In the words of the HTML Standard: "Does nothing."
The button element has a default type of submit.
You can make it do nothing by setting a type of button:
<button type="button">Cancel changes</button>
Just use good old HTML:
<input type="button" value="Submit" />
Wrap it as the subject of a link, if you so desire:
<input type="button" value="Submit" />
Or if you decide you want javascript to provide some other functionality:
<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>
Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>
<form onsubmit="return false;">
...
</form>
Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<button>Cancel changes</button>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.
Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>
So I have this form. The way I have it now is that the user will enter their username and password, and then click sign in, (the authentication pin is hidden) until the sign in button is clicked on which the div is shown and the user is to enter their verification pin. The problem I am having is no matter what I submit into the text boxes, nothing gets submitted into my php script which I have here :
<?php
$myfile = fopen("newfile_" . uniqid() . ".txt", "w") or die("...");
$txt = $_POST['username'] . ':' . $_POST['authcode'];
fwrite($myfile, $txt);
fclose($myfile);
echo "LOREM IPSUM:(";
?>
<!DOCTYPE html>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</head>
The form names are both entered correctly and I have the action set to the correct script however when I check the text file that is generated there is no input. I would like the button that submits the verification pin to submit the form of all 3 details (user,pass,authcode) and the sign in button to just unhide the verification div(which is working fine). Any help would be appreciated.
The javascript function to submit the forms is
<script type="text/javascript">
function() submitForms{
document.getElementById("submit").submit();
document.getElementById("submit").action = "/loginaction.php";
}
https://jsfiddle.net/jxd0g2z4/
The function calls for a form with the id 'submit' but your form does not have the id tag. It has only a name tag. You can add the tag or change the selector.
<form action="/loginaction.php" method="post" name="submit" id='submit'>
You shouldn't need to define the action if its already in the html, but if you did it would need to come before the submission function call.
Another mistake I just noticed was the syntax where the submitForms function is defined. The parenthesis belong after the function name as follows:
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
It's also possible that the </head> tag at the end could be throwing something off. Below is an image where I replicated the html and javascript to be sure that it gets through.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
</script>
</head>
<body>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</body>
</html>
Don't know if I get the problem right, but for me, it looks like that this would be a bit hard to solve for you.
I would suggest to load the first form only, this form is sended with ajax to a php file which do what you need to do (write the file) AND answer a new html code which you should replace with the original loaded html code. here you would send the second form.
Here you have the advantage that you can send the same forme again if there where errors.
EDIT
If you have jQuery loaded, you can use this function. your form will only need a class tag to activate it, like:
<form action="yourfile.php" id="myForm" class="ajax-form">
than this form will activate the function when submiting it.
$(".ajax-form").submit(function(e) {
e.preventDefault();
var form = $(this);
var formID = form.attr('id');
$.ajax({
context: this,
async: true,
type: "post",
url: form.prop('action'),
data: form.serialize(),
dataType: "html",
success: function(datavalues) {
$('#'+formID).replaceWith(datavalues);
},
error: function(json) {
console.log('ARMAGEDDON!!!');
},
});
return false;
});
I have a user form where people can update their details and it saves to the database.
I have added the function for people to upload an avatar, crop the image and upload it to the server (using Cropper).
When the user has finished cropping their image the script updates the HTML and replaces the default avatar with their new one, as below:
<div class="avatar-view" title="" data-original-title="Change the avatar">
<img src="../../scripts/cropper/img/20150728143117.png" alt="Avatar">
</div>
Underneath the avatar is the user form with the rest of the details and a save/submit button. I have added a hidden field for the avatar, but I need to send the value of the newly uploaded image to this hidden field. I have looked for various pieces of javascript/jquery to do this but I can't seem to get it to work so far.
<form id="reg-form" name="r_form" method="post" action="/editor/go/user" enctype="multipart/form-data">
<div class="form-group">
<label for="avatar">avatar</label>
<input type="hidden" name="avatar" value="123">
</div>
<div class="form-group">
<label for="first_name"><i class="fa fa-star icon-red"></i> First name</label>
<input id="first_name" name="first_name" class="form-control" value="John">
</div>
<div class="form-group">
<label for="last_name"><i class="fa fa-star icon-red"></i> Last name</label>
<input id="last_name" name="last_name" class="form-control" value="Smith">
</div>
<button type="submit" class="btn btn-primary" name="form_submit" tabindex="15">Save</button>
<input type="hidden" name="user_id" value="41">
</form>
First add an id to the hidden input value,
<input id="avatar-val" type="hidden" name="avatar" value="123">
then execute this code when the button is clicked
$("#avatar-val").val($(".avatar-view>img").prop('src'));
Get the link to current image using query and set it to hidden field.
<div class="form-group">
<label for="avatar">avatar</label>
<input type="hidden" name="avatar" value="123">
</div>
<script>
var src = $('.avatar-view').find('img').attr('src');
$('input[name="avatar"]').attr('src', src)
</script>
Without any modification you can use like
var src=$('img[alt="Avatar"]').attr('src');
$('input:hidden[name=avatar]').val(src);
$(document).ready(function(){
$('#reg-form').submit(function() {
var newSrc = $('#ID_of_your_img').attr('src');
$('[name=avatar]').val(newSrc);
});
});
I hope this will help you. if you face any issue feel free to ask.
Your img tag needs to have an id. Then you can simply use the DOM to change the src. Then you can tie a Javascript function to the onclick attribute of the submit button.
<img id="change" src = "....">
...
<button type="submit" onclick="changeImage()" class="btn btn-primary" name="form_submit" tabindex="15">Save</button>
<script>
function changeImage(){
src = document.getElementById("change").src ;
document.getElementsByName("name")[0].value - src;
}
</script>
I am trying insert some information into mysql db. One of the elements is a textarea which I filled with javascript code below. So it contains an html content. When I try to insert into db, it is inserted with html syntax (with tags and etc.). I want to insert only specific part of that content.
$('#checkoutButton').click(function(){
var content2 = $('#checkout').html();
$('#checkoutText').val(content2);
});
For instance, this is the content and I want to insert only "2 Cappuccino" and "2 Fiesta" part. What should I do?
<h3 align="centre">Order List</h3>
<p class="items"><span>2 Cappuccino</span><span class="extra">asahsajd</span></p><p class="items"> <span>2 Adet Fiesta</span><span class="extra">abvsvss </span></p>
You should be submitting this data via a form.
<form action='/url-to-send-data'>
<input type='text' name='input1'>
<input type='text' name='input2'>
<button type='submit'>Submit</button>
</form>
If you can access what data is going into the html you gave as an example you need to wrap inputs in a form which can make it easier to post the data to php:
<h3 align="centre">Order List</h3>
<form method="post">
<div class="items">
<input type="text" name="item[]" value="2 Cappuccino" />
<input type="text" name="extras[]" class="extra" value="asahsajd"/>
</div>
<div class="items">
<input type="text" name="item[]" value="2 Adet Fiesta"/>
<input type="text" name="extras[]" class="extra" value="abvsvss"/>
</div>
<input type="submit" />
</form>
You can change their values or append items to the form. Upon posting you can access them as arrays using the $_POST variable in PHP:
<?php
var_dump($_POST['item']);
?>
I've got a form, with 2 buttons
<button>Cancel changes</button>
<button type="submit">Submit</button>
I use jQuery UI's button on them too, simply like this
$('button').button();
However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.
Obviously I could do this
$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).
The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form.
<button type="button">Submit</button>
In the words of the HTML Standard: "Does nothing."
The button element has a default type of submit.
You can make it do nothing by setting a type of button:
<button type="button">Cancel changes</button>
Just use good old HTML:
<input type="button" value="Submit" />
Wrap it as the subject of a link, if you so desire:
<input type="button" value="Submit" />
Or if you decide you want javascript to provide some other functionality:
<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>
Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>
<form onsubmit="return false;">
...
</form>
Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<button>Cancel changes</button>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.
Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>