How to call HTML required attribute when the value is 0? - javascript

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>

Related

Add or remove the required attribute of an input field based on which option is selected

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>

how to avoid repetition of values in dropdown list while updating in php

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 } ?>

Keep the selected options after submitting the form

Good morning, I have a problem that is: I can not keep several options selected after submitting the form and I would like someone to help me.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>"><?php echo $reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>
this is my code to have the various options in the select box
You have to check if $_POST['utilizadores'] or $_GET['utilizadores'] it depends on your request type. I will use $_POST in here for explain my answer.
your select is multiple, you can use in_array function for checking that if result from db record is in array of $_POST['utilizadores']
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
**<option value="<?php echo $reg_sql['ID_USER']; ?>"
<?php
if(isset($_POST['utilizadores'])){
if(in_array($reg_sql['ID_USER'], $_POST['utilizadores'])){
echo 'selected';
}else{
echo '';
}
}
?>
>**<?php echo
$reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
You may be able to do it more efficiently if your database result also contains which rows are selected, but when you loop through, just add the selected="selected" attribute to the <option> tag.
Assuming your $_POST array exists in this scope, you can use the in_array function in PHP to determine if the option has been selected (docs).
The ternary based operation is as follows:
in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : ''
Which says "if the ID_USER is in the post array, then print the selected attribute, otherwise, print a blank string"
Putting it all together:
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>" <?= in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : '' $?>>
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
An example of how you can do this. Either add the "selected" string if yes or leave blank if no. You can also write selected="selected". You can do the same thing to set disabled or readonly.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<?php $selected = isset($reg_sql["mi_variable"]) ? "selected" : ""; ?>
<option value="<?php echo $reg_sql['ID_USER'];?>" <?php echo $selected; ?> >
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>

angularjs interferes with echoing php variable

I'm trying to pull a php variable ($purpose) and show it on the option select. The code that I have (see below) only works when I took out the element attribute ng-model="purpose". If I left the ng-model in-placed, the option select showed Purpose, which indicated php echoinng is did not go through. It seems echoing php variable and using angularjs conflicting with one another. Does anyone have this issue? Is there a workaround?
<select id="purpose" class="form-control custom-select" name="purpose" value="<?php if(isset($purpose) or !empty($purpose)) {echo $purpose;}?>" ng-model="purpose" autocomplete="on" required/>
<option <?php if($purpose == "") echo 'selected';?> value="">Purpose</option>
<option <?php if($purpose == "1030") echo 'selected';?> value="1030">1Exchange</option>
<option <?php if($purpose == "1040") echo 'selected';?> value="1040">Non-exchange</option>
<option <?php if($purpose == "1050") echo 'selected';?> value="1050">Financing</option>
</select>
Don't use value attribute when using ng-model. Just initialize a variable purpose & assign PHP variable to it. Like below:
<select ng-init="purpose = <?php if(isset($purpose) or !empty($purpose)) {echo $purpose;}?>" id="purpose" class="form-control custom-select" name="purpose" ng-model="purpose" autocomplete="on" required/>
<option <?php if($purpose == "") echo 'selected';?> ng-value="">Purpose</option>
<option <?php if($purpose == "1030") echo 'selected';?> ng-value="1030">1Exchange</option>
<option <?php if($purpose == "1040") echo 'selected';?> ng-value="1040">Non-exchange</option>
<option <?php if($purpose == "1050") echo 'selected';?> ng-value="1050">Financing</option>
</select>
While you might be able to get it work using this style, it is recommended to use JSON to populate data from back-end to angular.
<?php
$purpose_arr = array(
"1030" => "1Exchange",
"1040" => "Non-exchange",
"1050" => "Financing"
);
echo "<script> var purpose='" + json_encode($purpose_arr) + "'; </script>"
?>
html:
<select id="purpose" class="form-control custom-select" name="purpose" ng-model="purpose" autocomplete="on" required
ng-options="value as key for (key, value) in purpose" />
<option value="">Purpose</option>
</select>
controller:
$scope.purpose = purpose;

Multiselect without showing result on page

I use multiselect JS with php to get more than one selection of my form select.
Impossible for me not to show the selection' results on the select tags.
At least, if It's possible to show just the number of sélection(s) , it would be nice.
Thanks.
Sorry by impossible for to enter my code for the moment ! (seem not working)
<label for="showroom">Type/products* :</label>
<select class="form-control" id="materials" name="materials" multiple="multiple">
<?php while($prod=mysqli_fetch_assoc($prodQ)): ?>
<option value="<?php echo $prod['choc_id']; ?>"><?php echo $prod['choc_nom']; ?></option>
<?php endwhile; ?>
</select>
<script type="text/javascript">
$(document).ready(function() {
$('#materials').multiselect();
});
</script>

Categories

Resources