I'm looking for using Javascript in order to enable/disable submit button.
This button should respect both following conditions :
Enable : if checkbox is checked AND dropdown list value set
Disable : if both or one of previous conditions are not good (checkbox unchecked or date value not set)
This is my code :
function checkValid() {
var cbChecked = $(".fake-radio").is(":checked"); // check if checked
var selectelem = document.getElementById('year');
var btnelem = document.getElementById('document-button');
btnelem.disabled = !selectelem.value;
}
And this is my html part :
<table id="document-table">
<thead>
<tr>
<th>{% trans 'Choice' %}</th>
<th>{% trans 'Document title' %}</th>
</tr>
</thead>
<tbody>
{% for document in query_document %}
<tr>
<td><input type="checkbox" class="fake-radio" id="document-checkbox" name="DocumentChoice"
value="{{ document.id }}"></td>
</tr>
{% endfor %}
</tbody>
</table>
<select id="year" name="q1year" value="{{ request.get.q1year }}" required>
<option selected="selected">
<option value="" selected disabled hidden></option>
</option>
</select>
<button class="btn btn-default" id="document-button" type="submit"
name="UpdateDocument">{% trans "Submit" %}</button>
I'm pretty new with Javascript
EDIT :
I made this, is it true ?
function checkValid() {
var cbChecked = $(".fake-radio").is(":checked"); // check if checked
var selectelem = document.getElementById('year');
var btnelem = document.getElementById('document-button');
btnelem.disabled = !selectelem.value;
var dropdown_value = btnelem.disabled
$("#document-button").prop("disabled", !cbChecked || dropdown_value);
}
If I understand your situation correctly, then it looks like you have a minor logic error in your latest update. Consider revising your checkValid function like so:
function checkValid() {
var selectelem = $('#year');
var isChecked = $(".fake-radio").is(":checked"); // radio is checked
var selectHasValue = !!selectelem.val(); // select has value
// use de morgans law to compute disabled property
$("#document-button").prop("disabled", !(isChecked || selectHasValue));
}
You need to ensure that checkValid() is called when ever relevant form inputs are changed. You can do this by adding the following script:
$(function() {
// Apply validation logic when relevant fields change
$('#year, .fake-radio').change(checkValid);
checkValid(); // Apply validation logic on page load automatically
});
Also, for more on de morgans law, see this wiki article. Hope this helps!
you have to add on change event for your checkbox and select. and you don't need jquery for doing this, use pure js whenever you can.
this is what you need, take this as a reference and edit your code :
function checkValid(){
var check = document.getElementById("document-checkbox").checked;
var e = document.getElementById("year");
var select = e.options[e.selectedIndex].value;
if (select && check) document.getElementById("document-button").disabled = false
else document.getElementById("document-button").disabled = true
}
<body>
<input onchange="checkValid()" type="checkbox" class="fake-radio" id="document-checkbox" name="DocumentChoice" value="{{ document.id }}">
<select onchange="checkValid()" id="year" name="q1year" value="{{ request.get.q1year }}" required>
<option selected="selected">
<option value="x">x</option>
</option>
</select>
<button disabled class="btn btn-default" id="document-button" type="submit" name="UpdateDocument">submit</button>
</body>
Related
I have two button inside a form that I don't want to submit the form but add and remove table rows. One button is dynamically added.
I have tried many ways to prevent the submission but none seem to work. When I was getting the button by id and using an event listener it was ok but that did not work with button that get added after age load. I am trying to find a solution that will work with buttons. The one that loaded on page load and the ones that get added dynamically with JavaScript.
<table id="conditions-table">
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th></th>
</tr>
<tr>
<td>
<input id="condtitions-input"></input>
<select id="condtitions-level">
<option value="Mandatory">Mandatory</option>
<option value="Important">Important</option>
<option value="Support">Support</option>
</select>
</td>
<td>
<button id="add-condtition" onclick="addCondition(e); return false;">Add Conditions</button></td>
</td>
</tr>
</thead>
</table>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
<script>
var counter = 0;
function addCondition(e){
e.preventDefault()
var table = document.getElementById("conditions-table");
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var condtionsInput = document.getElementById("condtitions-input");
var condtionsInputValue = condtionsInput.value;
condtionsInput.value = "";
var selectedLevel = document.getElementById("condtitions-level");
var selectedLevelValue = selectedLevel.value;
cell1.innerHTML = `<input type="text" name="strategies_conditions[${counter}][name]" value=" ${condtionsInputValue}"></input>
<select>
<option ${(selectedLevelValue == "Mandatory") ? 'selected="selected"' : ""} value="Mandatory">Mandatory</option>
<option ${(selectedLevelValue == "Important") ? 'selected="selected"' : ""} value="Important">Important</option>
<option ${(selectedLevelValue == "Support") ? 'selected="selected"' : ""} value="Support">Support</option>
</select>`;
cell2.innerHTML = "<button class='remove-condition' onclick="removeCondition()">X</button></td>";
counter++;
return false;
};
function removeCondition() {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
};
The default type of a button is "submit"; just override that behavior by setting it to "button".
cell2.innerHTML = "<button type='button' class='remove-condition' onclick='removeCondition()'>X</button></td>";
You also need to define event as a parameter of the event handler function.
function removeCondition(event) {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
};
Just don't insert the argument e inside the onclick event in the markup you can apply an event using JavaScript like the following
btn.onclick = e => {
e.preventDefault();
}
<form>
<input type="text" name="" placeholder="Name">
<input type="submit" name="" id="btn">
</form>
or you can simply make a onclick event return false like the following
<form>
<input type="text" name="" placeholder="Name">
<input type="submit" name="" id="btn" onclick="return false">
</form>
to add an event to an element that doesn't exist yet on the DOM you need to know about event.target
here is a sample that might help you
document.addEventListener( "click", listenerFunction );
function listenerFunction(event){
var element = event.target;
// here you check for that auto generated element
if(element.tagName == 'A' && element.classList.contains("someBtn")){
console.log("hi");
}
}
All you really need to do is add:
<input type="submit" onclick="event.preventDefault();">
You probably want to handle it though so in total you'd probably do something more like this:
<script>
function myFunction(){
if (confirm("Are you sure you want to ...? This action cannot be undone.")) {
document.getElementById("myForm").submit();
}
}
</script>
<form method="post" action="/test" id="myForm">
<input type="submit" onclick="event.preventDefault();myFunction();">
</form>
This allows the user to click ok to proceed or cancel to not have it submit the form.
I have a problem ... here the create table's row each time user press Add button , How I can send all the data of the table to database at once cuz when press submit only last row inserted into database but not all the table but it should submit all rows with all data
I'm new in php so I don't have a lot in php code
this is the php code
<?php
include_once("dbinfo.php");
session_start();
$name= $_SESSION['user'];
if(isset($_POST['savepav'])){
date_default_timezone_set("Asia/Riyadh");
$pavdate= date("Y/m/d");
$pavtime=date("h:i:sa");
$pavloca=$_POST['pavlocation'];
$pavtype=$_POST['ddlPassport'];
$pavdist=$_POST['pavedist'];
$pavplan=$_POST['pavplan'];
$pavseve=$_POST['pavseverity'];
echo "<script>alert(' Pavement data saved successfully ');</script>";
$query="INSERT INTO `pevement`(`userName`, `plocation`, `pavType`, `padistr`, `pavplan`, `severity`, `pavdate`, `pavtime`) VALUES ('$name' ,'$pavloca', '$pavtype', '$pavdist' ,'$pavplan', '$pavseve', '$pavdate' ,'$pavtime')";
$result_query=mysqli_query($conn,$query);
}
?>
this is script code
<script>
function AddData() {
var rows = "";
var name = document.getElementById("locapavm").value;
var city = document.getElementById("sevepavm").value;
var plan = document.getElementById("planpavm").value;
rows += "<tr><td>" + name + "</td><td>" + city + "</td><td>" + plan + "</td><td><button onclick = deleterow(this)>Delete</button></td></tr>";
$(rows).appendTo("#list tbody");
}
function ResetForm() {
document.getElementById("person").reset();
}
function deleterow(el) {
$(el).closest('tr').remove();
}
</script>
and HTML
<html>
<div id = "data">
<form id = "person">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="col-12" style="width: 1514px">
<select id = "locapavm" name = "pavlocation" style="width: 26%">
<option value="">- Location -</option>
<option value="Runway 17">Runway 17</option>
<option value="Runway 35">Runway 35</option>
<option value="Runway 18">Runway 18</option>
<option value="Runway 36">Runway 36</option>
</select><br>
<div class="col-12">
<select id = "ddlPassport" name = "ddlPassport" style="width: 26%" onchange = "ShowHideDiv()">
<option value="">- Pavement Type -</option>
<option value="Flexible Pavement (Asphalt)">Flexible Pavement (Asphalt)</option>
<option value="Rigid Pavement (Concrete)">Rigid Pavement (Concrete)</option>
</select>
</div><br/>
<div class="col-12" style="width: 1514px">
<select id="pavdistrees" name="pavedist" style="width: 26%">
<option value="">- Distress selections - </option>
</select><br> </div>
<div class="col-12" style="width: 1514px">
<select id="sevepavm" name="pavseverity" style="width: 26%">
<option value="">- Severity -</option>
<option value="Low">Low</option>
<option value="Medium"> Medium</option>
<option value="High">High</option>
</select><br> </div>
<!----------------------------------------------------------------------->
<p class="auto-style1">Maintenance Plan:</p>
<textarea id="planpavm" name="pavplan" style="width: 572px; height: 129px" ></textarea><br>
<input id = "person" type = "reset" value = " Reset " onclick = "ResetForm()">
<input id = "button" type = "button" value = " Add " onclick = "AddData()">
</form>
</div>
<div id = "tab" style="width: 76%">
<table style="width: 96%" id = "list" cellspacing = "0px" cellpadding = "20px" text-align = "center">
<thead>
<tr>
<td>Location</td>
<td>Pavement Type</td>
<td>Type Distrees</td>
<td>Severity</td>
<td style="width: 396px">Maintenance Plan</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br><input type="submit" name="savepav" value="Submit"/>
</html>
I see you are using JQuery, so just based on that I think XHR would be your best bet. If you are adding it to the table with the "add" button, then I don't really see the point of the "Submit" button other than to redirect to a different page, so I will omit it just for this example, and edit my answer later if you have a different plan for it.
Your PHP code looks fine, other than it is vulnerable to an SQL injection attack. To prevent this, I would call the mysql_real_escape_string method on all of the strings you are putting in the database like so:
$pavloca=mysql_real_escape_string($_POST['pavlocation']);
$pavtype=mysql_real_escape_string($_POST['ddlPassport']);
$pavdist=mysql_real_escape_string($_POST['pavedist']);
$pavplan=mysql_real_escape_string($_POST['pavplan']);
$pavseve=mysql_real_escape_string($_POST['pavseverity']);
For the HTML, I would give your Add button the type of submit, then add the action and method attributes to your opening form tag like so:
<form id = "person" method = "POST" action = "/path/to/php/page">
where /path/to/php/page is the path to the PHP page that adds everything to the database.
And finally for the JavaScript.
Instead of having the onclick attribute on your Add button, I would remove that then just add this bit of JQuery to your script tag:
$("#person").submit(function(d){
d.preventDefault();
AddData(new FormData(d.target));
})
Then for your AddData function add an input parameter for the form:
function AddData(form)
P.S, a little trick after you've done that, you can actually get the values by the name attribute rather than an id like so:
var name = form["pavlocation"];
var city = form["pavseverity"];
var plan = form["pavplan"];
Then last but not least, add this little bit of code to the end of your AddData() function:
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.send();
And that should be it!
NOTE: I did not test any of this, so I apologize for any typos or syntax errors. If this does not work, I will edit my answer accordingly.
EDIT: There were a couple out-of-order tags in the HTML you posted, so I ran it through an IDE to clean it up a bit, and created a JSFiddle for it here: https://jsfiddle.net/djy9vget/2/
You will have to change the action="/path/to/php/page.php" bit to the actual path, but other than that this should work. I also noticed a typo in my original answer where XmlHttpRequest(); should be XMLHttpRequest();.
I also changed the ID of the Reset button from person (which is the same as the form), to reset.
I need to make sure that when you add a new ad, choosing a category, hiding unnecessary fields in the form. I understand that this is done in JS, but for the time being I don’t understand well, so I’ll tell you if anyone is good at it.
For example, I want the "Stage" to disappear when selecting "Houses and land":
Listing model:
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор')
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория')
region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область')
city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город')
district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район')
title = models.CharField(max_length=200, verbose_name='Заголовок')
landmark = models.CharField(blank=True, max_length=200, verbose_name='Ориентир')
description = models.TextField(blank=True, verbose_name='Описание')
stage = models.IntegerField(default=0, blank=True, verbose_name='Этаж')
rooms = models.IntegerField(default=0, blank=True, verbose_name='Количество комнат')
forms.py
class ListingForm(forms.ModelForm):
class Meta:
model = Listing
exclude = ('realtor',)
Form in template:
<form method="POST" novalidate enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Добавить" class="btn btn-secondary btn-block">
</form>
I looked in the browser structure of the form in the template:
<div class="form-group">
<label for="id_category">Категория</label>
<select name="category" class="form-control" title="" required id="id_category">
<option value="" selected>---------</option>
<option value="1">Квартиры</option>
<option value="2">Коммерческое</option>
<option value="3">Дома и участки</option>
</select></div>
The field structure I want to hide:
<div class="form-group">
<label for="id_stage">Этаж</label>
<input type="number" name="stage" value="0"
class="form-control" placeholder="Этаж" title="" id="id_stage">
</div>
I tried to do this, but it does not work yet:
<script>
$('#id_category').change(function () {
var optionSelected = $("option:selected", this);
var valueSelected = $(this).val();
if (valueSelected === 3){
$('#id_rooms').hide();
} else {
$('#id_rooms').show();
}
});
</script>
If you know, tell me, please, or an example of how it is done. Thank you in advance.
In a tag in your template, you'll need to use javascript to add an event listener on change of the first field.
In that event listener, if the value is the "selected category" use javascript to hide or show fields in the form.
For example if I had a form like this:
<form>
<select id="select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="field">Input Field</input>
</form>
In JQuery, this would look something like this:
$('#select').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if (valueSelected === 1){
$('#field').hide();
} else {
$('#field').show();
}
});
When i select an item from a dropdownmenu id like to view it in a input field, if another item is selected i want to add this to the input field separated by a comma.
Currently this is the html:
<div>
<input type="text" id="box" placeholder="Using..." style="width: 400px">
<select style="width: 180px" id="drop">
<option value="" disabled selected>Select</option>
{% for stuff in stuffs%}
<option value="{{stuff}}" onclick="ApplyField(drop,box)">{{stuff}}</option>
{% endfor %}
</select>
</div>
and the javascript:
<script>
function ApplyField(drop_id,box_id)
{
var e = document.getElementById(field_id);
var selectedItem = e.options[e.selectedIndex].text;
if (document.getElementById(box_id).text == "")
document.getElementById(box_id).text = selectedItem;
else
document.getElementById(box_id).text = document.getElementById(box_id).text + "," + selectedItem;
}
</script>
But somehow my script wont set the input box item to the selecteditem altough the code seems logical to me. This is my first time writing javascript so its likely that i missed something trivial. Any help is appretiated.
I believe that your drop_id and box_id are not the correct way to select the element in JavaScript. Also not quite sure what is going on with the {{stuff}} template to be honest
Can you use jQuery? If so, have a look at http://www.w3schools.com/jquery/html_val.asp
It was hard to find terms for a good search (so please excuse me if the topic has already been discussed) as well as an explicit title for this post.
I'm working on this external web page : https://espacepersonnel.bnf.fr/views/mes_notices.jsf (need to be logged)
and I'm trying to override the default selected option with the one which value="0". The custom js code I wrote does submit the form but only after the page has been loaded. Nevertheless I'd like to change the select value before this.
Here's the concerned code's part of this page (that of course I can't edit) :
<form id="noticeComp:mainForm" name="noticeComp:mainForm" method="post" action="/views/mes_notices.jsf" class="noticeForm" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="noticeComp:mainForm" value="noticeComp:mainForm">
<input type="hidden" name="noticeComp:mainForm:j_idt253" value="">
<input type="hidden" name="noticeComp:mainForm:j_idt254" value="false">
<!-- <div id="site"> -->
<!-- <div class="moncatagen"> -->
<!-- <div class="col2"> -->
<h1 class="h1small">
<span>
<select name="noticeComp:mainForm:j_idt256" size="1" onchange="submit()">
<option value="0">Toutes les notices</option>
<option value="1" selected="selected">Notices biblio.</option>
<option value="2">Notices d'autorités</option>
</select>
Notices
</span>
</h1>
</form>
And here's my own 'content_script' :
var elm;
var evt;
elm = document.getElementsByName('noticeComp:mainForm:j_idt256')[0];
evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
while(!document.getElementsByName('noticeComp:mainForm:j_idt256')[0].options[0].selected){
document.getElementsByName('noticeComp:mainForm:j_idt256')[0].options[0].selected="selected";
elm.dispatchEvent(evt);
}
Can you see a solution for me ? (Better if JS only)
Thank you very much for reading this post and answering it if you can.
Bigindian.
P.S : Pardon my english
N.B :
Result page :
result page
You can try the following:
get a reference to the select
loop over its options
if the value of the option is '0', select it. Otherwise, deselect it.
Example code:
var elm = document.getElementsByName('noticeComp:mainForm:j_idt256')[0];
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
for (var i = 0; i < elm.options.length; i++) {
var option = elm.options[i];
if (option.value === '0') {
option.setAttribute('selected', 'selected');
} else {
option.removeAttribute('selected');
}
}
elm.dispatchEvent(evt);
function submit() {
// code
console.log('gogo');
}
demo