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>
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 try to update this jquery script in pure js (with bootstrap 5). The goal is to not allow someone to click twice on the payment button. Sorry I am not very strong in js.
My goal is to have the same reaction that the jquery script.
I tried to follow the process on this page :
Disabling a button in vanilla JavaScript and in jQuery
Thank you
My current script
<form name="checkout_confirmation" action="http://............/Process" method="post" id="checkout_confirmation" role="form" onsubmit="return checkCheckBox(this)"><section class="checkout_confirmation" id="checkout_confirmation">
div class="text-end" id="process_button" class="processButton">
<button type="submit" data-button="payNow" class="btn btn-success">Confirmer la commande avec paiement</button> </div>
</div>
</form>
<script>
$('form[name="checkout_confirmation"]').submit(function() {
$('form[name="checkout_confirmation"] button[data-button="payNow"]').html('Confirm the payment').prop('disabled', true);
});
</script>
Now the script update
<script>
var button = document.getElementById('checkout_confirmation');
button.addEventListener('submit', function() {
alert('Confirm the payment');
});
button.disabled = false;
button.click(); // No output
button.prop("disabled", true);
</script>
setAttribute can be used in JavaScript to set the attribute of the button as disabled.
Element.setAttribute("disabled", true);
This can be used to disabled the button.
So when someone clicked on the submit button, you can disable the button till the data is processed.
Check the below demo code:
const btn = document.getElementById("submit-data");
btn.addEventListener("click", submitForm);
function submitForm(){
btn.setAttribute("disabled", true);
btn.innerText = "Submitting..";
let userName = document.getElementById("user-name").value;
console.log("Name: ", userName);
setTimeout(() => {
btn.removeAttribute("disabled");
btn.innerText = "Submit";
}, 3000);
}
<form type="POST">
<label for="user-name">Full Name</label>
<input type="text" id="user-name" placeholder="Your Full Name" />
<br /><br /><br />
<button id="submit-data">Submit</button>
</form>
You have two problems:
Submit events fire on form elements, not button elements.
getElementById gets an element by its id and neither your button nor your form has an id. (See this question).
Could you not use e.preventDefault() to stop the default behaviour of the button being pressed?
More can be read here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
I am trying to reset the form to blank values in the input textboxes after the data filled in the textbox have been searched.
<form id="myForm" class="mt-5" asp-controller="Leave" asp-action="GetAllLeaves">
<div class="form group col-md-6">
<label>Employee </label>
<div class="col">
<input type="hidden" id="employeeId" name="employeeId" />
<input type="text" name="employeeName" id="employeeName" value="#ViewData["CurrentFilterE"]" />
</div>
</div>
<button type="submit" class="btn btn-outline-success">Search</button>
<button type="reset" id="reset" class="btn btn-outline-primary">Reset</button>
</form>
I have tried bunch of different javascripts but none of them work after the search has been completed. They work fine before the search button is clicked. I am aware that there are questions already asked about this here and I have tried those codes but they don't work for me.
These are the different codes that I have tried. They don't work after the search button has been hit. Even refreshing the page does not delete the data in the input boxes.
function myFunction() {
document.getElementById("myForm")[0].reset();
};
$("#reset").click(function () {
$(this).closest('form').find("input[type=text], textarea").val("");
});
document.getElementById("reset").onclick = () => {
document.getElementById("myForm").reset()
};
let inputs = document.querySelectorAll('input');
document.getElementById("reset").onclick = () => {
inputs.forEach(input => input.value ='');
}
in your post method you need to have an IactionResult return type method and then you need to pass property name to ModelState.Remove method, not the value.
Either pass the property name in string, eg. ModelState.Remove("PropertyName"); or in the newer .NET framework, you can use nameof() keyword, eg. ModelState.Remove(nameof(model.Property));
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset.
Your default input value = "#ViewData["CurrentFilterE"]". Reset method restores a form element's default values.
This will help to reset the input:
html:
<form id="myForm">
<input type="text" name="employeeName" id="employeeName" value="test" />
<button id="reset" class="btn btn-outline-primary">Reset</button>
</form>
js:
document.getElementById("reset").onclick = function(e) {
document.getElementById("employeeName").value = "";
}
I ended up using the following
$("#reset").click(function () {
// this for normal <input> text box
$('#employeeName').attr("value", "");
//this for checkbox
document.getElementById('searchAprroved').removeAttribute('checked');
});
I have this form to select a csv file then upload it to mysql server:
<form class="ui input" enctype="multipart/form-data" method = "POST" action="trend_upload_csv.php" role = "form">
<input type = "file" name ="file" id="file" size = "150">
<input id="myBtn" class="ui small red button" type = "submit" class = "btn btn-default" name ="submit" onclick = "myFunction();" value = "Upload CSV" disabled />
</form>
Then a function to enable the upload button if there is a file selected, then disable the upload button once it was clicked then change the text of button to "uploading"
<script>
function myFunction() {
document.getElementById("myBtn").disabled = true;
document.getElementById("myBtn").value="Uploading";
}
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$('input:submit').attr('disabled',false);
}
});
});
</script>
My problem is it doesn't do the action to my php code and this results to disabling my upload button and changing text to "uploading" and nothing happens. How can I do the action before the onclick?
essentially you told the javascript that when I click on the button just change the button properties. not to upload the file. and the jquery code you have written is redundant as well.
you can do something like this in order to submit the form on click,
<script>
function myFunction() {
document.getElementById("myBtn").disabled = true;
document.getElementById("myBtn").value="Uploading";
document.getElementById("myForm").submit();
}
</script>
(don't forget to add an id attribute to form)
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.