Disabling the Submit button - javascript

I have a form which contains several elements and one of them being the select value element.However what i have done is that i have attached the quantity that has to be shown on the select menu, whose values comes from the database.
Example:
Suppose i have set 10 in my database for quantity then , the select element will show me options from 1-10.
Code:
<?php
if(#$dbqty>=10)
{
$selectbox='<p> Quantity: <select name="product_qty">';
for($i=1;$i<=10;$i++)
{
$selectbox.='<option value="'.$i.'">'.$i.'</option>';
}
$selectbox.='</select></p>';
echo $selectbox;
}
else if(#$dbqty<10 && #$dbqty>0)
{
$selectbox='<p> Quantity: <select name="product_qty">';
for($i=1;$i<=#$dbqty;$i++)
{
$selectbox.='<option value="'.$i.'">'.$i.'</option>';
}
$selectbox.='</select></p>';
echo $selectbox;
}
if(#$dbqty==null || #$dbqty==0)
{
echo '<input type="button" name="product_qty" value="Sold Out" disabled="disabled"/>';
}
?>
In the javascript part i have set a function which submit the form to a php file and loads its response text.
Code:
$(document).ready(function(){
$(document).on('submit','#submitform',function(event){
event.preventDefault();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...');
var data=$(this).serialize();
$.ajax({
type:'POST',
url:'../cart/index.php',
data:data,
success : function(content)
{
if ($('#ajaxview').find('#popupcart')) {
$('#popupcart').hide();
$('#ajaxview').append(content);
button_content.html('Add');
}
else
{
$('#ajaxview').append(content);
button_content.html('Add');
}
}
})
})
})
What i was trying to do is that when the quantity for the item comes out to be sold out the submit button gets disabled.Is it possible? If yes,How to do this one then?
Thanks!

A better approach, in my opinion, would be to get the data from database using javascript and then based on the retrieved value, use jQuery to enable/disable the button.

use this jquery to remove the submit events on the buttons which has value sold out
$('input[value="Sold Out"]').on('click',function(e){
e.preventDefault(); //stop the event
});
Or if the elements are appended dynamically, then you got to use delegated event handlers to attach the event. like below
$(document).on('click','input[value="Sold Out"]',function(e){
e.preventDefault(); //stop the event
});

$(document).on('submit','#submitform',function(event){
event.preventDefault();
var input=$("#submitform :input[name='product_qty']").val();
if(input==null)
$(this).find('button[type=submit]').prop('disabled', true);
}
This is what i did.It worked.However not a correct way to do this but it does the work.Stops the submit button to send any request.

Related

How can I change selected option based on database value?

In order to get you familiar with my work, I have table filled with data from database and it's basically CRUD - Create, Read, Update, Delete table.
Now, I have one table column where are EDIT and DELETE buttons placed. When I click on EDIT button, Bootstrap 5 modal pop-ups and inside of that modal there're <input> elements, also filled with data from database. Everything works fine (is filled correctly and based on ID of selected row) except that I can't get <select> to change its value on value from database.
Here's my <select> element (HTML):
<div class="mb-3">
<select name="carStatus" id="carStatus" class="form-control form-control-lg" required>
<option value="U obradi" selected disabled hidden></option>
<option value="Na cekanju">Na cekanju</option>
<option value="U procesu">U procesu</option>
<option value="Zavrseno">Zavrseno</option>
</select>
<div class="invalid-feedback">Niste unijeli status!</div>
</div>
This is js code where I handle values of input fields inside of modal:
// Fill in values and handle edit event
tbody.addEventListener("click", (e) => {
if (e.target && e.target.matches("a.editLink")) {
e.preventDefault();
let id = e.target.getAttribute("id");
editUser(id);
}
});
const editUser = async (id) => {
const data = await fetch(`action.php?edit=1&id=${id}`, {
method: "GET",
});
const response = await data.json();
//Here I am handling value of carStatus (<select>)
if(response.carStatus == "Na cekanju"){
selectElement("carStatus", 'Na cekanju');
}
else if(response.carStatus == "U procesu"){
selectElement("carStatus", 'U procesu');
}
else if(response.carStatus == "Zavrseno"){
selectElement("carStatus", 'Zavrseno');
}
else{
selectElement('carStatus', '');
}
//There are a lot of others element that I handle on the way like this:
document.getElementById("id").value = response.id; //This works
enter code here
//But I didn't want to put all of them because it'd take too much space...
//Here's my function where I am trying to handle value of selected element:
function selectElement(request, valueToSelect) {
let element = document.getElementById(request);
element.value = valueToSelect;
//Also I am getting the correct value -> when I select some row where Zavrseno is placed I really get Zavrseno in console...
console.log(response.carStatus);
}
};
Ohh, by the way there are 4 possible values that can be selected:
"U obradi", "Na cekanju", "U procesu", "Zavrseno"
I actually found out what's the reason why my code didn't work, even though it should've worked perfectly fine, because code itself was written correctly.
The problem was I also had the add modal at the same page with same id which was carStatus (id="carStatus"). Removing it was enough to fix the problem.
Now, the thing is I know that you can't have same id's at the same page, but can somebody explain me why's element which is placed inside Add modal causing problem when I am triggering this action on edit button?

Get the value of each value in input tag using onclick in javascript

I have a loop of button and input tags
while($row = mysqli_fetch_array($notifqry))
{
extract($row);
if($type_of_notif == '1')
{
echo '<button class="dropdown-item" onclick="notifview()">New Announcement!</button>';
echo '<input type="text" id="notifid" name="notifid" value="'.$notifid.'">';
}
}
and in my javascript
function notifview() {
var notifid = $('#notifid').val();
alert(notifid);
}
however, if I click the different button/links I only get the first row id only like this even i click the button w/ value of 3 or 4
id's need to unique for every input field. Also, if multiple input fields are created dynamically you will need to use event delegation to determine which button was clicked and then correspondingly extract that value.

javascript onchange with 2 different dropdown lists

Im pretty new with javascript programming.
I have some .php code, where 2 dropdown lists (in the same FORM) are populated by 2 different mysqli queries, this works without any problem.
Im trying to get javascript to handle the selected parts of the dropdown lists, with onchange, this works for only one dropdown list, and i cant really figure out how to get around this one.
This is the code that works with one dropdown menu, and it updates automaticly the page without submitting:
$chosen_location = $_GET['Lid'];
$chosen_car = $_GET['Cid'];
?>
<script type="text/javascript">
function changeDropDown(dropdown){
var location = dropdown.options[dropdown.selectedIndex].value;
*var car = dropdown.options[dropdown.selectedIndex].value;*
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
Part of the .php code:
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<option value = <?php echo ($location_id) ?> selected><?php echo ($location_name) ?></option>
<select size="1" name="form_car" id="form_car" onchange='changeDropDown(this);'>
<option value = <?php echo ($car_type_id) ?>><?php echo "" . ($car_class) . " - " . ($car_manufacturer) . " - " . ($car) . "" ?></option>
The italic marked I know will not catch the correct value, but this is where im at right now...
How is it possible to get an action URL with both selected values ? as this is going to be used in a mysqli query to show data from the actual selection
Thanks in advance... :)
Currently, you are submitting the form through JavaScript. If the selects are inside the form, their values will automatically be submitted when you submit the form. You don't even have to change the action of the form.
So, you can just generate a normal form (including submit button, if you will), and it will work. Then, add a little JavaScript sauce to make it submit automatically.
The code below does just that. JavaScripts adds a class to the body. This is a way to easily change styling based on JavaScript being enabled or not. In this case, I use it to hide the submit button, which is only needed in a non-JavaScript situation.
Then, I bind the on change handler, not unlike yours, to submit the form when a value is selected. By giving the selects a proper name, their values will automatically be added as intended.
Note how the event handlers are bound through code. You don't have to hardcode any calls to JavaScript in the HTML, so you can keep the HTML clean and separate (readability!).
// Bind to load event of the window. Alternatively, put the script at the end of the document.
window.addEventListener("load", function() {
// Indicate that JavaScript works. You can use this to style the document, for instance
// hide the submit button, if the form is automatically submitted on change..
document.body.classList.add("js");
// With JavaScript, you can automatically submit the form, but you still don't have to modify it.
var theform = document.getElementById("theform");
var selects = document.querySelectorAll("#theform select");
for (var i = 0; i < selects.length; ++i) {
selects[i].addEventListener("change",
function() {
alert("submitting now");
theform.submit();
});
}
});
.js button[type="submit"] {
display: none;
}
<!-- Just a form with selects is enough. You don't even have to have JavaScript to post this. -->
<form id="theform" action="test.php" method="get">
<select name="Lid">
<option>Example...</option>
<option>Use PHP,</option>
<option>to fill these.</option>
</select>
<select name="Cid">....</select>
<button type="submit">Post</button>
</form>
You can update your code to following
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var elCar = document.getElementById('form_car');
var location = elLocation.options[elLocation.selectedIndex].value;
var car = elCar.options[elCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
try to do this
<script>
// get select elements
var form_location_id = document.getElementById('form_location_id');
var form_car = document.getElementById('form_car');
// on change
form_location_id.addEventListener('change', changeDropDown1);
form_car.addEventListener('change', changeDropDown2);
</script>
And change the 'changeDropDown1' and 'changeDropDown2' to your handler function
try this
<script type="text/JavaScript">
var dropdownLocation = document.getElementById("form_location_id");
var dropdownCar = document.getElementById("form_car");
function changeDropDown() {
var location = dropdownLocation.options[dropdownLocation.selectedIndex].value;
var car = dropdownCar.options[dropdownCar.selectedIndex].value;
document.getElementById("form1").action = "test.php?Lid=" + location + "&Cid=" + car;
document.getElementById("form1").submit();
}
</script>
dropdownLocation et dropdownCar are outside the function to save time because this 2 vars need only to be set one time

html/javascript: Is there a way to force data inputted into a text input to go into its value attribute?

What i have is a div with text inputs. What i want to do is send the div's HTML code to the server to be used on another page like so:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
html: $("#form").html()
},
success: function (data) {
}
});
The thing is, if a user types in some data into the text inputs, that data is lost since its not part of the HTML. Is there a way i can force this data into the HTML? eg by using javascript to edit each input's value attribute?
Thanks in advance
Try the input event:
$(document).on('input', 'input.your_input', function() {
var that = $(this);
that.attr('value', that.val());
});
Inspect the input element and try type something:
$(document).on('input', '#textInp', function() {
var that = $(this);
that.attr('value', that.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="textInp" />
You can try sending the input values via parameters in the ajax function.
Try to run this snippet before making the call,
$("#form :text").attr("value",funcion(){
return $(this).val();
});
Instead of binding change event to all the input elements initially you can add the attribute before sending them to server.
You can try like this:
$("input").on('change', function() {
$(this).attr('value', $(this).val());
});

Change values in form submitted and the JQuery serialize function

Please look at the following code. When the form gets submitted, is it actually submitting the values I have entered i.e. val(50) or at the point it serialzies does it just get data from the form on the actual html page?
// stop all forms from submitting and submit the real (hidden) form#order
$('form:not(#order)').submit(function(event) {
alert($(this).attr('id'));
//event.preventDefault();
if($(this).attr('id')==='quick2a'){
alert('quick2a being submitted');
//submitQuick2a();
$('form#order input[name=custom_channels]').val(50);
var name = 'het-';
name += $('form#order input[name=platform]').val('astsk');
name += '-ga-';
name += $('form#order input[name=license]').val('floating');
$('form#order input[name=productname]').val(name);
$.post('/store/cart/add/ajax/', $('form#order').serialize(), function() {
document.location.href = '/store/checkout';
});
}else{
//
}
I want those values to be set in the form regardless of what is set by the user, am I doing this correctly?
Thanks all
Why not just construct the data directly instead of stuffing it into a form and then grabbing the values via serialize?
$('form').submit(function(event) {
if($(this).attr('id')==='quick2a') {
var data = {
'custom_channels': 50,
'platform' : 'astsk',
'license' : 'floating',
'productname' : 'het-astsk-ga-floating'
};
$.post('/store/cart/add/ajax/', data, function() {
document.location.href = '/store/checkout';
});
}else{
//
}
return false;
});
It gets the values from the HTML page... but by calling .val(...) you're setting the values on the HTML page, so your code will work as you want it to.

Categories