And my second question ,,
I have a simple modal box opening when I click on 'add users' . The modal box contains 3 submit buttons ( add, delete, and submit) . I have done this with the help of a javascript.
The html code is
<div id="overlay">
<div><a href='#' onclick='overlay()'>X</a>
<form action="" method="POST">
<table>
<tr>
<td style="width:120px;">
user<input style="width:100px;" name="u" type="text"/>
</td>
<td>
<input type ="submit" value = "add"> <input type="submit" value="delete"><br>
</td>
</tr>
<tr>
<td>
<select style="width:150px;">
<option value="abc">abc</option>
</select>
<br>
</td>
</tr>
</table>
</form>
<input type="submit" value="Submit"/> </div></div><a href='#' onclick='overlay()'>Click here to add user</a>
and my javascript is
function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";}
now my task is to to add a user when user types a name in the text field and press a add button, the same user name should come in the drop down list and similarly if user selects one name from the dropdown list and press the delete button , it should delete that name .
And finally if he press the submit button then only the modal box should close and the datas will be shown on my main page..
I have just started doing my task and am planning to implement these functionality using php and some file operations .
My first question is as user first press the add button ,, it will close the modal window and that is not what i am required ( I guess you understand my requirement ) Is there any way to solve this? Please help this newbie Thank you.
You have to add eventsListeners to the button and prevent their default behave.
(function(){
var addButton = document.getElementById("add_btn");
var deleteButton = document.getElementById("delete_btn");
addButton.addEventListener("click", addUser, false);
deleteButton.addEventListener("click", deleteUser, false);
})();
function addUser(event) {
event.preventDefault();
var element = event.target;
var userNameInput = document.getElementById("user_text");
var userName = userNameInput.value;
var usersList = document.getElementById("users_list");
var user = document.createElement('option');
user.value = userName;
user.innerHTML = userName;
usersList.appendChild(user);
usersList.selectedIndex = usersList.length - 1;
userNameInput.value = "";
}
function deleteUser(event) {
event.preventDefault();
var usersList = document.getElementById("users_list");
usersList[usersList.selectedIndex].remove();
}
Here an example I wrote on jsFiddle of your code:
jsFiddle
Make your form submits using AJAX...default submit btn will refresh the page.
I assuming when you add/delete a user...you are actually saving them in the db.
1.When you press 'Add' btn...make an ajax call to the backend with the user details and save it and send a callback whether the user has been added successfully or not.
2. On the add user callback...you can call a function to update the drop-down list.
Related
I have this school application, I want to add 100 questions to the database, the normal thing done is add, one after the other., that is I will click submit 100 times....exhausting right.... Now, I want to create an application that I will have to query the database once, that is the submit button will have an add more button beside, but if I click to add more, it should make another text area show below......but if I click save, it should save to the database
<form method="post" action={{route('save.question', $subject->slug)}} >
#csrf
<textarea name="questions"></textarea>
<button type='submit'>Submit</button>
<button type=''>Add more question</button>
</form>
There's some approaches, but I prefer:
If click on Add more question button, add a textarea input to DOM
If click on Submit, add all textarea values to a javascript array
Stringify the array
Send it into an input that hidden
Decode that input value in PHP with json_decode()
So:
let questionsContainer = document.querySelector("#questions-container");
let addQuestionTextarea = document.querySelector("#add-question-textarea");
addQuestionTextarea.onclick = () => {
let textarea = document.createElement("textarea");
questionsContainer.appendChild(textarea);
}
let submit = document.querySelector("#submit");
submit.onclick = () => {
collectValues();
}
function collectValues(){
let allTextareas = questionsContainer.getElementsByTagName('textarea');
allTextareas = [...allTextareas]
let allValues = [];
allTextareas.forEach((textarea)=>{ allValues.push(textarea.value) });
document.getElementById('questions-array').value = JSON.stringify(allValues);
document.getElementById("form").submit();
}
textarea{
display:block;
margin: 8px;
}
<div id="questions-container">
<textarea></textarea>
</div>
<button id="add-question-textarea">Add more question</button>
<form method="post" action={{route('save.question', $subject->slug)}} id="form">
#csrf
<input type="text" id="questions-array" hidden name="questions">
</form>
<button id="submit">Submit</button>
(I know the questions is a bit long but I do believe solution is easy, so would really appreciate it if someone can help me have a look)
I am trying to write a school system, where you can enter a student's name, year, grade, on a webpage, and save the student's info to produce a list. I would like it to have two "buttons" on the webpage:
One is "save and next", i.e. if you finished entering one student info, click this, the info get saved and the webpage renew to enter the next student info.
Second is "save and finish", i.e. if this is the final student you want to enter, click this and the last student info get saved, and webpage is redirected to the next page where it shows a list of all student info.
To achieve this, in JSP, I used two HTML forms, and one of them I used javascript to try to submit to servlet, But I must have done something wrong because it does not work properly:
Here are my codes:
InputGrade.jsp:
<html>
<head>
<title>Title</title>
</head>
<body>
The first form: used input labels for users to enter info, also used input label to create a submit button "save it next":
<form action = "InputGradeServlet" method="POST">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name = "stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="submit" value="save and next"/>
</td>
</tr>
</table>
<input type="text" name = "flag" style="display: none" value="1"/>
</form>
The second form include the "save and finish" button, but use javascript to submit the information: (I think where the problem is)
User still enter student info in the first form, but the javascript function use getElementById function to acquire the info in first form
<form name="form2" action ="InputGradeServlet" method="POST" >
<input type="text" name = "flag" style="display: none" value="2"/>
<button onclick="finSaveFunc()">Finish and submit</button>
<script>
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
document.stName.submit();
document.Subject.submit();
document.Grade.submit();
}
</script>
And in the Servlet, a list created to add the students the user entered
public class InputGradeServlet extends HttpServlet {
List<Student> inputStList = new <Student>ArrayList();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if user press "save and next" button, form one is submitted, and servlet do the action of saving student to the list and redirect to the same JSP file i.e. redirect the the same webpage again of entering the next student:(also might be problematic)
if (request.getParameter("flag").equals("1")) {
request.getParameter("Grade");
...... (get other info: name, year ect)
inputStList.add(findstudent); //add student entered to the list
response.sendRedirect("InputGrade.jsp");
}
}
}
If user press "save and finish", i.e. submitting the second form, and servlet again add the final student entered to the list and redirect to the next webpage showing the whole list:
}else if (request.getParameter("flag").equals("2")) {
request.getParameter("Grade");
....
inputStList.add(findstudent);
request.getSession().setAttribute("inputStList",inputStList);
response.sendRedirect("ShowList.jsp"); }
This is where it gets problematic: when submitting the first form hitting "save and next" button it works fine, but when submitting the second from hitting "save and finish" button, it returns error.
Therefore I would really appreciate it if some can help me have a look?
There are many reason that's why you can get a NullpointerException.
Rule of Thumbs : If you want to compare a string then first check if it is not null.
According to your requirement I am giving a solution that how can you do that.
Suppose your form be like:
<html>
<head>
<script>
function _submit(flagVal) {
document.getElementById('flagValId').value=flagVal;
document.getElementById('someFormId').submit();
}
</script>
</head>
<body>
<form action = "InputGradeServlet" method="POST" id="someFormId">
<table>
<tr>
<td>
Enter Student Name: <input type="text" id="stName" name ="stName" />
</td>
<td>
Enter Subject: <input type="text" id="Subject" name = "Subject" />
</td>
<td>
Enter Grade: <input type = "text" id="Grade" name = "Grade" />
</td>
<td>
<input type="button" value="save and next" onclick="_submit('1')"/>
<input type="button" value="save and exit" onclick="_submit('2')"/>
</td>
</tr>
</table>
<input type="hidden" id="flagValId" name = "flag" value=""/>
</form>
</body>
</html>
Now when you click save and next button, then it set flagVal 1 and if we click save and exit button then it sets flagVal 2. After setting the flagVal it submits the form. After submitting your from you should check first that what is your flagVal. So in doPost method
if (request.getParameter("flag")!=null && request.getParameter("flag").equals("1")) {
//Add your student in this block and show the input page again.
response.sendRedirect("InputGrade.jsp");
}else if (request.getParameter("flag")!=null && request.getParameter("flag").equals("2")) {
//Add your student in this block and show the list.
response.sendRedirect("ShowList.jsp");
}
Hope that helps.
You don't get form1 values. You post form2 values so you get null error.
Try it please:
function finSaveFunc() {
var stName = document.getElementById("stName")
var Subject = document.getElementById("Subject")
var Grade = document.getElementById("Grade")
var newForm = document
.getElementById("form2")
.appendChild(stName)
.appendChild(Subject)
.appendChild(Grade);
newForm.submit();
}
Just a very brief explanation of what a part of my code does:
I have two buttons that do different things.
One of them lets the user search through the table/database for whatever he/she wants to search for
The other lets the user insert things into the database
WHAT I'M TRYING TO DO:
I'm trying to check to see which button the user clicked on so that the appropriate code will be executed.
I've been looking around and pretty much everywhere I go, people are suggesting to use isset(), but it's not working for me. Perhaps I don't fully understand what isset() does, but doesn't it basically check to see whether a variable is set?
Here's my code:
<script>
function show(x, y){
<!-- Do something -->
}
</script>
<form>
<button name = "sButton" type = "button" onclick = 'show("searchForm", "insertForm");'>Perform Search</button>
<button name = "iButton" type = "button" onclick = 'show("insertForm", "searchForm");'>Insert Data</button>
</form>
<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
<!-- Do something -->
</form>
<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
<!-- Do something -->
</form>
<!-- This is the test2.php page -->
if(isset($_POST['sButton'])){
<!-- Do something -->
}
else{
<!-- Do something -->
}
To test it, I had the if statement print "Checked" and the else print "Not checked". When I run my code, it prints "Not checked". What am I doing wrong and what should I be doing?
Thanks in advance!
You are not passing your buttons sButton or iButton into test2.php because your second and third form do not have them as input. Only inputs inside each particular form will be submitted. and your form that has the buttons has no action only the buttons call the JS function.
What I suggest you do is to add hidden fields for each form that you are submitting to test2.php as follows:
<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
<input type="hidden" name = "sButton" value="sButton" />
<!-- Do something -->
</form>
<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
<input type="hidden" name = "iButton" value="iButton" />
<!-- Do something -->
</form>
This way your test2.php should work.
Add an
<input type="hidden" name="sButton" />
into the search form, and a
<input type="hidden" name="iButton" />
into the insert form.
After that. You need to submit the (selected) form in the show(...) javascript function
Use this:
onclick = 'show(this.name, "searchForm", "insertForm");'
Example:
<button name = "sButton" type = "button" onclick = 'show(this.name, "searchForm", "insertForm");'>Perform Search</button>
function show(name, x, y){
alert(name);
if(name === "sButton"){
do this....
}
}
Output:
sButton
DEMO
http://codepen.io/tuga/pen/RPNaXY
I'm not sure what you're trying to do, but I don't see why the buttons are in a form at all. Consider attaching the listeners dynamically, adding a name or ID to the buttons so you can tell which one was clicked then hide or show the forms depending on which was clicked:
// The buttons don't seem to need to be in a form, so use some other
// container so you don't need to worry about a useless form being
// submitted
<div id="buttonContainer">
<button id="searchButton">Perform search</button>
<button id="insertButton">Insert data</button>
</div>
// Forms for testing
<form id="searchForm"><input value="search"></form>
<form id="insertForm"><input value="insert"></form>
and the code:
<script>
// Hide and show forms depending on which button was clicked using the
// button's ID
function showForm(event) {
// If the search button was clicked, show the search form and hide the
// input form
if (/search/.test(this.id)) {
document.getElementById('searchForm').style.display = '';
document.getElementById('insertForm').style.display = 'none';
// If the insert button was clicked, do the opposite
} else {
document.getElementById('searchForm').style.display = 'none';
document.getElementById('insertForm').style.display = '';
}
}
// Attach listeners to the buttons
window.onload = function() {
Array.prototype.forEach.call(document.querySelectorAll('#searchButton, #insertButton'),
function(button) {
button.addEventListener('click', showForm, false);
}
);
// Hide the forms
Array.prototype.forEach.call(document.querySelectorAll('#searchForm, #insertForm'),
function(form) {
form.style.display = 'none';
}
);
}
</script>
I have a list of users that in the end of each line in the table I added two links("href"):
one for "update" user and secend for "delete" user.
So for enable that I added a call to javascript function that capture the ID of user
and insert it to some form that I created before (form with only one "hidden" field),
and then the function activated submit() operation to the server part (asp.net code).
I checked and the submit() operation works ok(checked with respons.write()...)
But I know how to recognize a submit form button inside IsPost by ask what the value
of the submit button (for example: if(Request.Form["ExpertButton"]== "delete"){..some code here....})
But when I activate submit() with javascript, how could I recognize post?
I tryed with the value of the hiiden field but it's not capture this
and it skiped of the if statement....
the list of users code:
foreach(var row in db.Query(displayExperts,nameOfExpert))
{
<tr>
<td class="dispExpertActScreen">#row.ExpertID</td>
<td class="dispExpertActScreen">#row.name</td>
<td class="dispExpertActScreen">#row.password</td>
<td class="dispExpertActScreen">#row.allowBonds</td>
<td class="dispExpertActScreen">#row.allowStocks</td>
<td class="dispExpertActScreen">#row.allowExchangeTraded</td>
<td class="dispExpertActScreen">#row.allowMutualFund</td>
<td class="dispExpertActScreen">update</td>
<td class="dispExpertActScreen">delete</td>
</tr>
}
the form code:
<form method="post" name="deleteExpert" style="font-size: medium; margin-top: 10%" dir="rtl">
<input type="hidden" name="expertID" id="expertID" value="">
</form>
the javascript code:
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('deleteExpert').submit ();
}
</script>
the asp.net code:
#{
var db = Database.Open("MyProjectSite");
var display="no";
var displayExperts="";
var nameOfExpert="";
var category="";
if(IsPost)
{
if(Request.Form["ExpertButton"]== "search")// this is by button!!!
{
some code.....
}
//Response.Write("^^^^^^^^^^^^^^^^^^^^^");
if(Request.Form["ExpertButton"] != "")// this need to be by javascript submit() method !!! here I need to recognize it.
{
var id=Request.Form["expertID"];
Response.Write("^^^^^^^^^^^^^^^^^^^^^"+id);
var deleteQuery="DELETE FROM InvestmanExperts WHERE ExpertID=#0";
db.Execute(deleteQuery,id);
}
}
db.Close();
}
thanks...
Why not puting another hidden input value :
<input type="hidden" name="txtJavascriptMode" id="txtJavascriptMode" value="">
then in your javascript code :
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('txtJavascriptMode').value = 'true';
document.getElementById('deleteExpert').submit ();
}
</script>
and in your serverside you can checkout
if(Request["txtJavascriptMode"] == "true")
{}
In this jsfiddle
http://jsfiddle.net/littlesandra88/eGRRb/
have I submit buttons that are auto-generated. Each table row gets an unique ID number, and if needed each submit button can get the same unique number as well.
Question
The problem is that there are multiple submit buttons, so how do I know which was pressed?
HTML
<form action="" method="post">
<table class="alerts tablesorter" id="accTable" cellspacing="0">
<thead>
<tr class="header">
<th class="activity-header"> A </th>
<th class="activity-header"> Signed </th>
<th class="activity-header"> </th>
</tr>
</thead>
<tbody>
<tr class="row" id="7249">
<td class="activity-data">7249</td>
<!-- tablesorter can't sort a column with check boxes out-of-the-box, so it needs something to sort on. That is why the span tag is here -->
<!-- a jquery script is watching the state of the checkbox, so when clicked the value in the span is updated -->
<td class="checkbox"> <span style="display:none;">0</span> <input name="signed" type="checkbox" > </td>
<td class="edit-column"> <input value="Save" type="submit" name="7249"></td>
</tr>
<tr class="row" id="61484">
<td class="activity-data">61484</td>
<td class="checkbox"> <span style="display:none;">1</span> <input name="signed" type="checkbox" checked > </td>
<td class="edit-column"> <input value="Save" type="submit" name="61484"></td>
</tr>
</tbody>
</table>
</form>
JavaScript
$(document).ready(function() {
$("#accTable").tablesorter();
// :checkbox stops from executing the event on the save button. Same as input[type=checkbox]
$('#accTable input:checkbox').click(function() {
// insert 1 or 0 depending of checkbox state in the tag before the input tag. In this case <span> is before <input>
// this is done so tablesorter have something to sort on, as it doesn't support checkbox sort out of the box.
var order = this.checked ? '1' : '0';
$(this).prev().html(order);
$(this).parents("table").trigger("update");
});
});
// sends the form content to server side, and stay on page
$('form').live('submit', function() {
alert('test');
// don't redirect
return false;
});
You could use delegate():
$('form').delegate('input:submit','click',
function(){
alert(this.name);
return false;
});
JS Fiddle demo.
Edited to address question in the comments, from OP:
Would it be possible to display 0 or 1 as the state of the associated checkbox with this approach?
Yeah, that's possible, though it's a little more long-winded than I'd like:
$('form').delegate('input:submit','click',
function(){
var idString = this.name;
var checkboxState = $('#' + idString).find('input:checkbox').is(':checked');
if (checkboxState == true){
alert('1');
}
else {
alert('0');
}
return false;
});
JS Fiddle demo.
You will need to add an onClick handler to each button that does:
$(this).closest('form').data('submit_name', this.name);
Assign a function to the click event of the submit buttons. That function should simply store the clicked button's value in a variable. Inside the submit event of the form, check the value of that variable. The submit event will fire after the click event so you should be able to get the expected result.
Demo here
The thing to note here is that that different browsers behave differently when dealing with multiple submit buttons; specially when you hit enter to submit the form. I think my example takes care of this.
As you are using one form and using $('form').live('submit', function() { and both submit buttons are in the same form so its not possible in submit event. You have to use click event or two form tags.
Here is how I solve this,
HTML
<form id="my-form" ...>
....
Save
Save and add another
</form>
Javascript
$('.btn-submit-form').on('click', function(ev){
ev.preventDefault();
var $form = $(this).attr('href');
if ($form.length > 0) {
$form.trigger('submit', {'submitBtn': $this});
}
});
$('form').on('submit', function(ev, extra) {
if (extra && extra.submitBtn) {
var submitVal = extra.submitBtn.attr('data-value');
} else {
var submitVal = null;
}
// submit the form as you want with submitVal as one of the fields.
});
The advantage here is that your form only submits on the submit event and not on click event. This way you can have one common function to submit the form whether you click a button, hit return in a form field or submit it pragmatically.
I also like to make things as generic as possible and turn them into patterns. This two functions can work across your whole project if you come up with some patterns like naming each submit button with value as .btn-form-submit and having a data-value attribute to store the value.