I am working on a dynamic array inside a table which means the table appears based on user input. Users need to fill this table and then click submit. I need to place javascript here to check if the user didn't select anything or didn't write in any column. If so, the user should not be able to proceed.
<form action="klr.php" method="post" name="myform" >
<?php
for ($i = 1; $i <= $de; $i++) {
?>
<tr>
<td>Tube</td>
<td>
<select id="in4-<?php echo $i; ?>" name="t1[<?php echo $i; ?>]" onclick="getText3(<?php echo $i; ?>)" onchange="getText39(<?php echo $i; ?>)" onmouseout="getText89(<?php echo $i; ?>)">
<option value="0">0</option>
<option value="12">12</option>
<option value="18">18</option>
<option value="24">24</option>
<option value="75">75</option>
</select>
</td>
<td>
<input type="text" name="t2[<?php echo $i; ?>]" id="in1-<?php echo $i; ?>" onblur="getText3(<?php echo $i; ?>)" onchange="getText39(<?php echo $i; ?>)" onmouseout="getText89(<?php echo $i; ?>)"/>
</td>
<td>
<select name="a1[<?php echo $i; ?>]" id="in2-<?php echo $i; ?>" onclick="getText3(<?php echo $i; ?>)"onchange="getText39(<?php echo $i; ?>)" onmouseout="getText89(<?php echo $i; ?>)" >
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</td>
</table>
I only provided the code of the first row of the table in which the user selects values. In the second column users can enter some values and in the third column users can select a value again. I need to place javascript in three of these columns
It sounds like you just wanted to verify if everything inside the form element was validated. Here are two fiddles I worked up to get you started:
1) Regular Javascript
function formCheck() {
var form = document.getElementById('mainForm'),
inputs = form.getElementsByTagName('INPUT'),
selects = form.getElementsByTagName('SELECT'),
i,
errors = [];
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value.match(/^\s*$/)) {
errors.push(inputs[i].title + ' was not set');
}
}
for (i = 0; i < selects.length; i++) {
if (selects[i].selectedIndex === 0) {
errors.push(selects[i].title + ' was not set');
}
}
if (errors.length > 0 ) {
alert(errors.join('\n'));
return false;
}
alert('success!');
return true;
}
http://jsfiddle.net/fstreamz/3Decx/4/
2) With JQuery
function formCheck() {
var formElements = $('#mainForm').find('input, select'),
errors = [];
$.each(formElements, function(i, el) {
if ($(el).val().match(/^\s*$/)) {
errors.push($(el).prop('title') + ' is blank!');
}
});
if (errors.length > 0 ) {
alert(errors.join('\n'));
return false;
}
alert('success');
return true;
}
http://jsfiddle.net/fstreamz/w5KG3/4/
A few notes: 1) It checks every input or select element inside a form element with id="mainForm" so you'd have to add that to your form (next to name="myForm"). 2) I added a title attribute to the input/select elements so I could show that in the error message as a reference. 3) It checks for whitespace in input boxes and consider that invalid. 4) in the jsFiddle, it returns false even in success so the form doesn't submit for demonstration purposes. That should be changed to true if you use it.
Related
Basically I have a form in which a certain amount of input fields and selections (ingredient, quantity, unit of measure) are generated by a loop. Now I would like to remove the attribute required from the quantity field only when the associated selected unit of measure is 'j.e.'
<form method="post">
<?php
for ($n = 0; $n < $num; $n++) {
$data = $DB->query("SELECT * FROM ingredient"); ?>
<select name="list_ingr[]" required> <?php
while ($ingrs = $data->fetch()) { ?>
<option value="<?php echo $ingrs['id_ingr'] ?>"><?php echo $ingrs['name'] ?></option> - <?php
} ?>
</select>
Qt. <input type="number" name="list_quant[]" step="1" min="1" required>
<select name="measure[]">
<option value="none"></option>
<option value="gr">gr</option>
<option value="ml">ml</option>
<option value="j.e.">j.e.</option>
</select><br>
<?php
}
?>
<br>
<input type="submit" name="confirm" value="Confirm">
</form>
I have little to no experience when it comes to client side programming so I have no idea how to implement this; I tried looking for a bunch of JS/jQuery codes but none seem to work :/
Any help is appreciated!
Add a change event listener to the form to handle changing the required attribute of the input element beside the select element whose value changed.
document.querySelector('form').addEventListener('change', e => {
if (e.target.matches('select')) {
e.target.previousElementSibling.required = e.target.value !== 'j.e.';
}
});
If I understand correctly,
This is my working solution:
I set id for your Qt inputs. And I removed one with jQuery.
<form method="post">
<?php
for ($n = 0; $n < $num; $n++) {
$data = $DB->query("SELECT * FROM ingredient"); ?>
<select name="list_ingr[]" required> <?php
while ($ingrs = $data->fetch()) { ?>
<option value="<?php echo $ingrs['id_ingr'] ?>"><?php echo $ingrs['name'] ?></option> - <?php
} ?>
</select>
Qt. <input id="qt_<?php echo $ingrs['id_ingr'] ?>" type="number" name="list_quant[]" step="1" min="1" required>
<select name="measure[]">
<option value="none"></option>
<option value="gr">gr</option>
<option value="ml">ml</option>
<option value="j.e.">j.e.</option>
</select><br>
<?php
}
?>
<br>
<input type="submit" name="confirm" value="Confirm">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#qt_2').remove(); //For example, to remove qt_2
});
</script>
I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>
I have a drop down list where I'm populating data from the database.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<!-- <option value="" selected="selected">?</option> -->
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
</div>
My form,
How values are populated from the database,
My database table,
I want to add a validation when the title form is populated with the value "0", which is "?", it should call the HTML required attribute.
Or I would like to disable the option with the '?' mark.
How can I do achieve this?
I have managed to find a solution to my issue. I managed to do it without any JS or Jquery. Just added an if statement.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<?php if(($this->session->userdata('Title') == 0)) { ?>
<option value="" selected disabled><?php echo $row->value; ?></option>
<?php } else{?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php } ?>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
you can use jquery like this: you can use an id for ? like id="yourZeroOption" and then
$('option#yourZeroOption').each(function() {
if ($(this).isChecked())
$("select").attr("required", true);
else
alert('this filled cannot be ?');
});
since what you asked was'nt clear enough this code might helf and if you manipulate this code you can get what you want from your code. but this for sure will give you a gist of what you should do. by the way this code does not need to submit it will show the alert before that
If this is in Laravel there is a way to catch certain number to be pass. In this case, try with greater_than rule with a custom message.
Example
$this->form_validation->set_rules('title', 'Title', 'greater_than[0]');
$this->form_validation->set_message('greater_than', 'Please select one of these value');
Note: JS validation works, But keep mind it's not always.
You should mark your <select> field as required, then the first option as disabled (and selected):
<select required>
<option value="" selected disabled>?</option>
<option value="1">Mr.</option>
<option value="2">Miss</option>
<option value="3">Mrs.</option>
</select>
This will make the first entry work as a placeholder basically.
we cant make it require with 0 value it can be done only if value=""
here is my idea,
<form action="/action_page.php">
<select required>
<option value="0">?</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select option:selected").val("");
});
</script>
<style>
I have php page for vehicle search filter which have 2 types of vehicle that is RV's and campervans and also have two selects
<div class="fields">
<p>Vehicle Type</p>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<?php if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){ ?>
<option value="<?php echo $vt ?>" <?=isset($_GET['car_type'])&&$_GET['car_type']==$vt?'selected':'';?> ><?php echo $vt ?></option>
<?php }
} ?>
</select>
</div>
<div class="fields">
<p>Total No. of Passengers*</p>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<option <?php if(#$_REQUEST['passengers'] == 1){?>selected<?php }?>>1</option>
<option <?php if(#$_REQUEST['passengers'] == 2){?>selected<?php }?>>2</option>
<option <?php if(#$_REQUEST['passengers'] == 3){?>selected<?php } ?>>3</option>
<option <?php if(#$_REQUEST['passengers'] == 4){?>selected<?php }?>>4</option>
<option <?php if(#$_REQUEST['passengers'] == 5){?>selected<?php }?>>5</option>
<option <?php if(#$_REQUEST['passengers'] == 6){?>selected<?php }?>>6</option>
<option <?php if(#$_REQUEST['passengers'] == 7){?>selected<?php }?>>7</option>
<option <?php if(#$_REQUEST['passengers'] == 8){?>selected<?php }?>>8</option>
</select>
</div>
How do I do that with jQuery or php if I choose "Rv" in the first select? The second select would show me 8 passengers . If I choose Campervan in the first select, the second select would show me 5 passengers..
I would probably do something along these lines:
<?php
$number_of_passengers = 8;
if(!empty($_REQUEST['car_type'])) {
$number_of_passengers = $_REQUEST['car_type'] == 'Campervans' ? 5 : 8;
}
$passengers = 0;
if(!empty($_REQUEST['passengers'])){
$passengers = (int) $_REQUEST['passengers'];
}
?>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<option value="RV/Motorhome">RV/Motorhome</option>
<option value="Campervans">Campervans</option>
</select>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<?php
for($i = 1; $i <= $number_of_passengers; $i++) {
?>
<option
<?php
if($i == $passengers) {
echo ' selected ';
}
?>
>
<?php echo $i ?>
</option>
<?php
}
?>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#car_type').change(function() {
$("#passengers").children().removeAttr("selected");
if ($(this).val() === 'Campervans') {
$('#passengers option:nth-child(n+7)').hide();
} else {
$('#passengers option').show();
}
});
</script>
There are cleaner ways of doing this but this should serve to get the point across.
Few things to note about the PHP:
See how I check if the $_REQUEST key is available using empty - this avoids having to use # which is generally not a good idea.
I am using a loop to echo the options in the passenger select to avoid code repetition because typing that out 8 times is boring ;-)
Hope this helps!
yes you need to add javascript code for that.
insert below code in your page and check if this is what you want?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$('.car').on('change', function(){
if($(this).val() === 'RV/Motorhome'){
$('.half').find('option').show()
}else if($(this).val() === 'Campervans'){
$('.half').find('option').slice(6).hide();
}
})
</script>
I'm writing a script to add div block after clicking the add button.
Everything is fine, however after adding second block that incrementing.
For example: After second clicking that adding 4 block overall 6.
After clicking the removing that is deleting the last one also.
var removeBtn = $("#removeField");
$("body").on("click", "#addField", function(e) {
e.preventDefault();
var room = $(".room-type").first();
var count = removeBtn.data("count");
if (count > 0) {
removeBtn.data("count", count++).attr("data-count", count++);
} else {
removeBtn.data("count", 1).attr("data-count", 1);
}
room.clone(false).appendTo(".room-type");
});
$("body").on("click", "#removeField:not([data-count=0])", function(e) {
e.preventDefault();
var count = removeBtn.data("count");
if (count > 0) {
$(".room-type").data("count", count--).attr("data-count", count--).last().remove();
}
});
HTML
<div class="form_element select room-type">
<div class="duo_left">
<label class="form_name"><?=pll__('Room type')?></label>
<select name="room-type[]" class="selectpicker multi-fields">
<?if($single != null) :?>
<option value="Single Room">Single Room</option>
<? endif; ?>
<?if($double != null) :?>
<option value="Single Room">Double Room</option>
<? endif; ?>
<?if($deluxe != null) :?>
<option value="Single Room">Deluxe Room</option>
<? endif; ?>
<?if($deluxe_double != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($executive_room != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($gloria_room != null) :?>
<option value="Single Room">Gloria Room</option>
<? endif; ?>
</select>
</div>
<div class="duo_right">
<label class="form_name"><?=pll__('Number')?></label>
<select name="room-number[]" class="selectpicker multi-fields">
<option value="0" selected>0</option>
<? for ($i=1; $i<=10; $i++) : ?>
<option value="<?=$i?>"><?=$i?></option>
<? endfor; ?>
<option value="10+">10+</option>
</select>
</div>
</div>
you need to append to a parent div, add an additional div
like "container" on top of your "room-type"
and append your clone to it
room.clone().appendTo("#container");
also before removing check the length of your "room-type" class
here is a working fiddle for you
https://jsfiddle.net/fxabnk4o/12/