JavaScript use same function for different id's - javascript

I have a form with several date fields. These date fields are actual text fields as I want to control the date structure from the start.
<div class="form-group col-md-6 col-xs-13">
<?php echo form_error('eindDatum'); ?>
<label for="eindDatum"><?php echo $this->lang->line('eindDatum'); ?><small class="text-info"><?php echo ' ' . $this->lang->line('datumNotatie'); ?></small></label>
<input type="text" name="eindDatum" id="eindDatum" class="form-control date" placeholder="DD-MM-YYYY" required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-[0-9]{4}">
</div>
<div class="form-group col-md-6 col-xs-13">
<?php echo form_error('aanvangDatum'); ?>
<label for="aanvangDatum"><?php echo $this->lang->line('aanvangDatum'); ?><small class="text-info"><?php echo ' ' . $this->lang->line('datumNotatie'); ?></small></label>
<input type="text" name="aanvangDatum" id="aanvangDatum" class="form-control date" placeholder="DD-MM-YYYY" required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-[0-9]{4}">
</div>
I was looking for a formatter online to automatically insert the - (dash) between the structures. But my knowledge of JavaScript is really limited. I tried with using the class selector but that does not seem to work at all.
var date = document.getElementsByClassName('date');
And then I added a class of date to the input text fields
I (am trying to) work with this https://codepen.io/tutsplus/pen/KMWqRr
Any help would be greatly appreciated. If possible tell me why you are approaching it in a specific way so I can learn from your experience.

In the link you shared they are applying the function to a single element as they are getting it by id.
In your case you tried to get it by its class in that case it won't work because the date variable will contain a collection of elements, so you need to loop over this collection to add the event listener properly to each element.
Your code should look like this:
var dates = document.getElementsByClassName('date');
Array.from(dates).forEach(function(element) {
element.addEventListener('input', inputFunction);
element.addEventListener('blur', blurFunction);
});
Note:
I made two functions for both events, all you need to do is to put the code inside the eventlisteners in your link respectively inside these two functions:
function inputFunction(e) {
//The input event code will be here
...
}
function blurFunction(e) {
//The blur event code will be here
...
}

Related

call js inside php not worked

I have issue with script js inside php so i want ipnut get the somme of the value return by function js in dispaly in input with condition in php inside the input in below my script php:
function getSum(){
let NotePresence= document.getElementById("NotePresence").value;
let NoteValidation= document.getElementById("NoteValidation").value;
let NoteEvaluation= document.getElementById("NoteEvaluation").value;
let t=NotePresence+NoteValidation+NoteEvaluation;
return t;
}
calling in php:
<div class="form-group" style="display: flex">
<input readonly="" style='width: auto' type="text"
name="NoteFinale" id="NoteFinale"
class="form-control" maxlength="2"
value="<?php echo '<script type="text/javascript">getSum();</script>';?>
size="4" />
<label for=""> /80</label>
</div>
Thanks in advance
You can't put a script element inside an attribute value.
If you want to assign a value to the attribute from JS, then:
Put the script somewhere after the element in the DOM
Find the element with DOM methods (e.g. document.getElementById)
Assign the value to the element with DOM
Note, however, that since you should know the initial values for the three elements you are reading from, you should be able to eliminate JS entirely and just do this with PHP.
$NotePresence = 50;
$NoteValidation = 100;
$NoteEvaluation = 150;
<input name="NotePresence" value="<?=htmlspecialchars($NotePresence)">
<input name="NoteValidation" value="<?=htmlspecialchars($NoteValidation)">
<input name="NotePresence" value="<?=htmlspecialchars($NotePresence)">
<input name="NoteFinale" value="<?=htmlspecialchars($NotePresence + $NoteValidation = $NoteEvaluation)">
That is, assuming you want to combine them when the document loads.
If you want to do it later, then…
In JavaScript you would need to move the code into a function that you call when a suitable event (e.g. change on an input or submit on a form occurs).
In PHP you would need to move the code to the place the data is submitted to and combine the data from $_POST.

how to access more than one text box which is in onchange Javascript

<html>
<head>
<script type="text/javascript" src="datetimepicker_css.js"></script>
<script type="text/javascript">
function sel(){
var y=document.getElementById("demo1").value;
document.getElementById("cal").innerHTML=y;
}
</script>
</head>
<?php
for($i=0; $i<2; $i++){
?>
<input type="text" name="doi" required="" placeholder="current inspect date" id="demo1" onchange="sel()" required>
<img src="cal.gif" alt="failed to load img">
<?php
}
?>
<p id="cal"></p>
</html>
(datetimepicker_css.js is my calender file used to select date); two textbox id=demo[after select of calender it print correct when i select other calender first text is affected. I need to access two text value after selecting each calender.
when i select other calender first text is affected.
Again same issue of same IDs applied on multiple elements in a single page.
As per valid markup you should always put unique id on your elements and that should be unique.
When you don't do it what happens in the element lookup in your case, the browser goes to find the element with the given id with:
var y=document.getElementById("demo1").value;
so when browser gets the first one it returns it's value as code suggests but when you try to get the second one it still returns the first one.
Why?
With given ids browser stops the element lookup in the document when it finds first element with the supplied id.
What can be done?
You have two options either you give unique IDs or use a common classname like:
with IDs:
<?php
for($i=0; $i<2; $i++){
?>
<input type="text" name="doi" required="" placeholder="current inspect date"
id="demo<?php echo $i+1?>" onchange="sel()" required>
<a href="javascript:NewCssCal('demo<?php echo $i+1?>','ddmmmyyyy','arrow')">
<img src="cal.gif" alt="failed to load img">
</a>
<?php
}
?>
This id="demo<?php echo $i+1?>" would produce unique IDs.
With common class name:
<?php
for($i=0; $i<2; $i++){
?>
<input type="text" name="doi" required=""
placeholder="current inspect date" class="demo" onchange="sel(this)" required>
<a href="javascript:NewCssCal('demo','ddmmmyyyy','arrow')">
<img src="cal.gif" alt="failed to load img">
</a>
<?php
}
?>
You can see a change here onchange="sel(this)" you can pass this element in the function and change the function to accept arguments like:
<script type="text/javascript">
function sel(el){ // <-----el is the element 'this'
var y=el.value;
document.getElementById("cal").innerHTML=y;
}
</script>
You can use jQuery selector here and update values on change event of every input box provided that you should use some common selector like name, class etc.
See below code, where i have used class="doi" for multiple inputs and bind change event handler to it. iterate inputs to get values for on change event of any input box.
Note:- It is not recommended to use same id for multiple elements. This may cause to issue in scripts. Please remove id="demo1"from input as this will create multiple inputs with same id.
<input type="text" name="doi" required=""
placeholder="current inspect date"
onchange="sel()" required class="doi">
<input type="text" name="doi" required=""
placeholder="current inspect date"
onchange="sel()" required class="doi">
jQuery : register handler
$(function(){
$('input.doi').change(function(){
$("#cal").empty(); // clear cal para
//set value of each input to cal
$('input.doi').each(function(){
$("#cal").append($(this).val() + " , ");
});
});
});

Options for auto setting a date input field

When presenting a user with a date input form
<input type="date" class="form-control" name="date" value="{{ old('date') }}">
Most of the time although not always the user needs to enter todays date.
What are my options for setting the default value to todays date.
Im using Blade, PHP, Bootstrap, Laravel, CSS, HTML
If any of them resources have something to handle this.
Thanks in advance for any feedback it's appreciated.
You can use PHP to echo the date:
<?php $today = date("m/d/Y"); ?>
<input type="date" class="form-control" name="date" value="<?php echo $today; ?>">
This will echo a date in the format of Month/Date/Year, e.g. 12/31/2000
The documentation here explains in more detail on how to format the date
The function old() takes a second parameter, the default. Using the link provided by user Chris, it looks like you want the format d/m/Y. With that in mind, the following should do the trick.
{{ old('date', date('d/m/Y')) }}

Dynamically fill multiple input fields from MySQL depending on the drop list item selected

I've searched through the site for this but am coming up empty handed. Here is what I am trying to do:
User selects one of a series of options from a drop list
Two input fields change to reflect this selection, filling the input boxes with data pulled from my database
See the image below for a visual representation of what I mean:
I know that I am going to need JavaScript for this solution, but my JS skills are not so hot (and I think I am having a momentary lapse of brain power today)!
Here's the code that I have so far (don't worry about the outdated PHP):
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_category = $row['item_category'];
$item_title = $row['item_title'];
$item_price = $row['item_price'];
$item_description = $row['item_description'];
echo "<option value=\"".$item_id."\">".$item_title."</option>";
}
?>
</select>
<script>
function update_txt() {
price = document.getElementById('item').selectedIndex.value;
document.getElementById('item_details').value = price;
document.getElementById('item_price').value = price;
}
</script>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
Any help is greatly appreciated! Let me know if you need any clarification. :)
I would json encode the row and store it as a data-attribute on the option, then read the attribute on the selects change event:
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_title = $row['item_title'];
echo "<option value=\"".$item_id."\" data-json='" . json_encode($row) . "'>".$item_title."</option>";
}
?>
</select>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
<script>
$('#item').on('change', function() {
var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
$('#item_details').val(selected.item_description);
$('#item_price').val(selected.item_price);
});
</script>
You can use a combination of PHP, AJAX and JavaScript (or jQuery).
The general idea is as follows:
User selects an option(s)
JavaScript is used to detect the selection and the option(s)
selected
AJAX gets the options selected, formats it and passes it to a PHP "page"
PHP does the SQL queries and passes the values back
AJAX gets those values and populates the current page using standard JavaScript methods
There's a good tutorial here which shows how it fits together: http://www.tizag.com/ajaxTutorial/ajax-mysql-database.php. I would use prepared statements instead of the SQL queries shown in this example though.

Indirect Population of Textarea in HTML Form Using PHP

I am working on an "Update User Data" form, which should reflect the initially entered information stored in the database into the textarea, and can be changed if the user wishes to. While I'm doing so, I have a concern - is directly writing value = <?php //some code ?> the safest bet?
I was trying to invoke a function to place my PHP code in that instead, but apparently it's just displaying the function's name.
Here's my code snippet:
<div>Date of Birth: </div>
<input id="dob" type="date" onFocus="emptyElement('status')" value="reflect_data('dob');">
where the function reflect_data is defined as -
function reflect_data(elem) {
//query and some code to access the data and store into $member
if (elem == "dob") {
echo $member['DOB'];
exit();
}
NOTE : A newbie to PHP, any advice would be welcome. Thanks. :)
You use php code in a JS function. That won't work that way and is impractical. Simple:
<input id="dob" type="date" onFocus="emptyElement('status')" value="<?php echo htmlspecialchars($member['DOB']); ?>">
is the best solution.

Categories