jQuery - best way to add/remove form section dynamically - javascript

I have following form group:
<div id="edu_row1">
<div class="form-group">
<label class="sr-only" for="edu_row_1_name"><?php _e('Name','ja'); ?></label>
<input type="text" class="form-control" name="edu_row[1][name]" value="<?php echo $edu_item['name']; ?>" id="edu_row_[1]_name" placeholder="<?php _e('Enter school name','ja'); ?>">
</div>
<div class="form-group">
<label class="sr-only" for="edu_row_from_date_1"><?php _e('From date','ja'); ?></label>
<input type="text" class="form-control" value="<?php echo $edu_item['from_date']; ?>" id="edu_row_date_1_from" name="edu_row[1][from]" placeholder="<?php _e('From date','ja'); ?>">
</div>
<div class="form-group">
<label class="sr-only" for="edu_row_to_date_1"><?php _e('To date','ja'); ?></label>
<input type="text" class="form-control" value="<?php echo $edu_item['to_date']; ?>" id="edu_row_date_1_to" name="edu_row[1][to]" placeholder="<?php _e('To date','ja'); ?>">
</div>
<input type="text" class="form-control" value="1" id="edu_row_<?php echo $i; ?>_id" name="edu_row[1][id]" placeholder="<?php _e('ID','ja'); ?>">
</div>
What would be the best way to be able to add/remove buttons to add another section with jQuery, with proper indexes? I tried using the code from http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove, but that seems way too compliacted.

var clone = $('#edu_row1').clone(),
number = $('.edu_row').length+1;
//add new id to the clone
clone.attr('id', 'edu_row'+number)
//change label
.find('label').each(function(){
$(this).attr('for', $(this).attr('for').replace('_1_', '_'+number+'_'));
});
//change inputs inside the form-group
clone.find('.form-group > input').each(function(){
$(this).attr('id', $(this).attr('id').replace('_1_', '_'+number+'_'));
$(this).attr('name', $(this).attr('id').replace('[1]', '['+number+']'));
});
//change latest input
clone.find('input.form-control').last().each(function(){
$(this).attr('id', $(this).attr('id').replace('_1', '_'+number+''));
$(this).attr('name', $(this).attr('id').replace('[1]', '['+number+']'));
$(this).val(number);
});
//insert the clone after the last
clone.insertAfter('.edu_row:last');
This requires an additional class though:
<div id="edu_row1" class="edu_row">
...
</div>

Related

Q: Calculate two inputs with javascript

I have created the following code and on the last 3 inputs, I would like to calculate INPUT1 with INPUT2 and automatically get the result on INPUT3.
At the moment it's not working ofc, but if I change the INPUT3 to suddenly it works, but ofc I cannot get any data to be posted onto the database. How can I output the result of the calculation without having to use a span tag?
Here is the Code.
<script>
function divideBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num2 % num1;
}
</script>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Create new Route</h2>
</div>
<p>Enter the route<i><strong>"YYYY-MM-DD</i></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($reason_err)) ? 'has-error' : ''; ?>">
<label>Reason</label>
<input type="text" name="reason" class="form-control" value="<?php echo $reason; ?>">
<span class="help-block"><?php echo $reason_err;?></span>
</div>
<div class="form-group <?php echo (!empty($startdest_err)) ? 'has-error' : ''; ?>">
<label>Start Destination</label>
<input type="text" name="startdest" class="form-control" value="<?php echo $startdest; ?>">
<span class="help-block"><?php echo $startdest_err;?></span>
</div>
<div class="form-group <?php echo (!empty($enddest_err)) ? 'has-error' : ''; ?>">
<label>End Destination</label>
<input type="text" name="enddest" class="form-control" value="<?php echo $enddest; ?>">
<span class="help-block"><?php echo $enddest_err;?></span>
</div>
<div class="form-group <?php echo (!empty($startkm_err)) ? 'has-error' : ''; ?>">
<label>INPUT 1</label>
<input type="text" name="startkm" class="form-control" id="firstNumber" value="<?php echo $startkm; ?>">
<span class="help-block"><?php echo $startkm_err;?></span>
</div>
<div class="form-group <?php echo (!empty($endkm_err)) ? 'has-error' : ''; ?>">
<label>INPUT 2</label>
<input type="text" name="endkm" class="form-control" id="secondNumber" onChange="divideBy()" value="<?php echo $endkm; ?>">
<span class="help-block"><?php echo $endkm_err;?></span>
</div>
<div class="form-group <?php echo (!empty($totalkm_err)) ? 'has-error' : ''; ?>">
<label>INPUT3</label>
<input type="text" name="totalkm" id="result" class="form-control" value="<?php echo $totalkm; ?>">
<span class="help-block"><?php echo $totalkm_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
If i change it from:
<div class="form-group <?php echo (!empty($totalkm_err)) ? 'has-error' : ''; ?>">
<label>Total Km</label>
<input type="text" name="totalkm" id="result" class="form-control" value="<?php echo $totalkm; ?>">
<span class="help-block"><?php echo $totalkm_err;?></span>
</div>
To this it works but ofc as I said no data is posted:
<div class="form-group <?php echo (!empty($totalkm_err)) ? 'has-error' : ''; ?>">
<label>Total Km</label>
<span type="text" name="totalkm" id="result" class="form-control" value="<?php echo $totalkm; ?>">
<span class="help-block"><?php echo $totalkm_err;?></span>
</div>```
#KIKO Software I solved after reading your comment a couple of times :) code that was changed "document.getElementById("result").value" and it solved the issue now upon changing the last input it automatically calculates the result from those two inputs mentioned before, and this was the result I was looking for.
<script>
function divideBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").value = num2 % num1;
}
</script>
Thank you for your help :)

JS not running inside modal after dynamically change of it's id

I'm using bootstrap modal and I'm calling a autocomplete function inside of it, it all works well when it's set like this:
Button that has a data-target to call the id of the modal:
data-target="#modalAdicao"
And the div with the id set to match the data-target:
id="modalAdicao"
But because it's called inside a PHP foreach and I need keep the information, I have to set the id of the modal like the id of the mysql line I'm dealing with, like this:
data-target="#modalAdicao<?php echo htmlspecialchars($idModal); ?>"
And:
id="modalAdicao<?php echo htmlspecialchars($idModal); ?>"
After this, the information is kept but the js stops working, it's like I never called it, but it's there, like it always been:
<script src="js/procura-paciente.js"></script>
Anyone can help?
When modal opening, the id is changed and the modal is re-drawn. But the js event is defined.
Try to use this
$(document).on('input','.busca', limpaCampos);
The for loop generate many #busca, the id is unique. Change to use class instead. For example
php form
<form id="novoAgendamento" method="POST" action="include/novo_agendamento.php">
<div class="form-inline">
<div class="form-group">
<label for="busca" class="sr-only">Identidade</label>
<input type="text" id="busca" data-id="<?php echo htmlspecialchars($idModal); ?>" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control busca" required>
</div>
<div class="form-group">
<label for="nascimentoPaciente" class="sr-only">Nascimento</label>
<input type="text" id="nascimentoPaciente" placeholder="Nascimento" name="nascimentoPaciente" class="mx-sm-69 form-control" required>
</div>
</div>
<div class="form-group">
<label for="nomePaciente"></label>
<input type="hidden" name="nomePaciente" class="form-control nomePaciente">
<input type="hidden" name="cpfPaciente" class="form-control cpfPaciente">
<input type="hidden" name="horaPaciente" value="<?php echo htmlspecialchars($horarios[$i]); ?>" class="form-control horaPaciente">
<input type="hidden" name="dataPaciente" value="<?php echo htmlspecialchars($data_agendamento_convert); ?>" class="form-control dataPaciente">
<input type="hidden" name="medicoPaciente" value="<?php echo htmlspecialchars($medico_completo); ?>" class="form-control medicoPaciente">
<input type="text" placeholder="Nome do Paciente" class="form-control nomePaciente2" disabled="">
<label for="observacaoPaciente"></label>
<input type="text" name="observacaoPaciente" placeholder="Observação" class="form-control" required>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-secondary">Fechar</button>
<button type="submit" class="btn btn-primary">Agendar</button>
</div>
</form>
js
$(function() {
$('#tableteste').on('input', '.busca', function(){
var busca = $(this).val();
var form = $(this).parents().eq(2);
if(busca == ""){
form.find('.nomePaciente').val('');
form.find('.nomePaciente2').val('');
form.find('.rgPaciente').val('');
form.find('.nascimentoPaciente').val('');
form.find('.cpfPaciente').val('');
}
});
.....
});

PHP Multiple loops to read multiple tables and display in single select element HTML?

I need to display all the values from two table in my HTML input. It has info about a user called recruit who has info from two multiple tables. But only interview_id and course_id I need to display all values in the select menu. The problem is I am just getting last value of each loop. So it displays only one value in echo $interviewrow[date_time]; and echo $courserow[name];
Sorry if the formatting is wrong.
Here is my php read values from database which is just before the select element:
<?php
$interviewlist = $dbcon->exec("select idinterview, date_time from interview");
for($i=0;$i<$interviewlist;$i++){
$interviewrow=$dbcon->data_seek($i);
?>
<?php
$recruit= $dbcon->exec("select * from recruit where user_id=".quote_smart($userid));
if($recruit>0){
$recruitrow=$dbcon->data_seek($i);
}
$recruitcourse= $dbcon->exec("select idcourse, name from course where idcourse=".quote_smart($recruitrow[course_id]));
if($recruitcourse>0)
$recruitcourserow=$dbcon->data_seek($i);
$courselist= $dbcon->exec("select * from course");
for($i=0;$i<$courselist;$i++){
$courserow=$dbcon->data_seek($i);
?>
Here is my html in javascript which appears if select type is recruit which is just after the php read.
else if( $(this).val() == 'Recruit' || $(this).val() == 'Recruit-Edit'){
$('.new-field').remove();
$('.new-input').append(' <div class="new-field"> <input type="hidden" name="idinterview" value="<?php echo $interviewrow[idinterview];>"><div class="form-group" id="opt"><label class="col-sm-2 control-label">Date</label><div class="col-sm-10"><select class="form-control" id="date" name="date"><option selected disable>Choose Date</option><option><?php echo $interviewrow[date_time]; ?></option></select></div></div> <?php } ?><div class="form-group"><label class="col-sm-2 control-label">Applied For</label><div class="col-sm-10"><input name="applied" type="text" class="form-control" value="<?php echo $recruitrow[applied_for]; ?>"></div></div> <div class="form-group"><label class="col-sm-2 control-label">CV</label><div class="col-sm-10"><input accept="application/pdf" class="enable-attache" data-geometry="150x150#" data-value="[<?php echo htmlentities($recruitrow[file]); ?>]" data-uploadurl="<?php echo ATTACHE_DOMAIN; ?>/upload" data-downloadurl="<?php echo ATTACHE_DOMAIN; ?>/view" data-uuid="<?php echo $uuid; ?>" data-expiration="<?php echo $expiration; ?>" data-hmac="<?php echo hash_hmac('sha1', $uuid.$expiration, ATTACHE_SECRET); ?>" type="file" name="cv" id="cv" /></div></div><div class="form-group"><label class="col-sm-2 control-label">Phone</label><div class="col-sm-10"><input name="phone" type="text" class="form-control" value="<?php echo $recruitrow[phone]; ?>"></div></div> <div class="form-group"><label class="col-sm-2 control-label">Date Applied</label><div class="col-sm-10"><input name="datea" type="date" class="form-control" value="<?php echo $recruitrow[date_applied]; ?>"></div></div> <input type="hidden" name="idcourse" value="<?php echo $courserow[idcourse];?>"><div class="form-group" id="opt"><label class="col-sm-2 control-label">Course Enrolled (if any)</label><div class="col-sm-10"><select class="form-control" id="course" name="course"><option selected disable><?php echo $recruitcourserow[name]; ?></option><option><?php echo $courserow[name]; ?></option></select></div></div><?php } ?></div>');

Boostrap date picker not work after clone (using jQuery-Cloneya)

I have a question would like to ask you why Bootstrap date picker is not work with other after I've clone its. I am using jQuery-Cloneya Plugin to clone the form, you can visit this website to know about it : https://github.com/yapapaya/jquery-cloneya
Below is the code of cloneya jQuery plugin which I have try :
<script type="text/javascript" src="<?php echo base_url() . F_JS; ?>jquery-cloneya.js"></script>
<script>
$('#contain-education').cloneya({
limit : 5,
valueClone : true,
dataClone : true,
deepClone : true,
clonePosition : 'after',
serializeID : true,
defaultRender : false
});
$('#contain-exp').cloneya();
$('#contain-lang').cloneya();
$('#contain-language').cloneya();
</script>
Below is a code to clone :
<script type="text/javascript">
$('.contain-education').each(function() {
var $wrapper = $('.wrap-education', this);
$("body").on("click",".add-education", $(this),function(e) {
$('.append-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
$('.append-field .remove-edu-field', $wrapper).click(function() {
if ($('.append-field', $wrapper).length > 1)
$con = confirm("Are you sure you want to delete this?");
if($con==true){
$(this).parent('.append-field').remove();
}
});
});
</script>
Here is a HTML code :
<div class="row" id="contain-education">
<div class="toclone">
<div class="form-group">
<label class="col-xs-3 control-label" for="school_name[]">School name <span class="error">*</span></label>
<div class="col-xs-8">
<input id="textinput" name="school_name[]" placeholder="" value="<?php echo set_value("school_name"); ?>" class="form-control input-md" type="text">
<span class="error"><?php echo form_error("school_name"); ?></span>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="program_name[]">Major <span class="error">*</span></label>
<div class="col-xs-8">
<input type="text" class="form-control input-md" value="<?php echo set_value("program_name"); ?>" placeholder="" name="program_name[]" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="education_level[]">Education level <span class="error">*</span></label>
<div class="col-xs-8">
<select class="form-control input-md" name="education_level[]">
<option value="">-- Education level --</option>
<?php foreach($education_level->result() as $row): ?>
<option value="<?php echo $row->education_level_id; ?>"><?php echo $row->name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="start_edu_date[]">Start date <span class="error">*</span></label>
<div class="col-xs-8">
<input type="text" class="form-control date_pick" id="start_edu_date" value="<?php echo set_value("start_edu_date"); ?>" name="start_edu_date[]" required="required">
<span class="error"><?php echo form_error("start_edu_date"); ?></span>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="end_edu_date[]">End date <span class="error">*</span></label>
<div class="col-xs-8">
<input type="text" class="form-control date_pick" id="end_edu_date" value="<?php echo set_value("end_edu_date"); ?>" name="end_edu_date[]" required="required">
<span class="error"><?php echo form_error("end_edu_date"); ?></span>
</div>
</div>
<div class="form-group">
<div class="col-xs-11">
<span class="pull-right">
<i class="glyphicon glyphicon-remove"></i>
<i class="glyphicon glyphicon-plus"></i>
</span>
</div>
</div>
</div>
</div>
thanks you for your help.
You haven't mentioned what plugin you have used. Lets say your plugin is invoked like this:
$('input.date_pick').datepicker();
Then, it will only be applied to the existing inputs, not inputs that will be created in the future.
When the new inputs are created by cloning, you can invoke your datepicker:
$('#contain-education').cloneya({
// ... options
}).on('clone_after_append', function(event, toclone, newclone) {
$(newclone).find('input.date_pick').datepicker();
});

How to pass for loop php to javascript

I have multiple edit records. I used script below to compare the value of textbox1 in textbox 2. But the problem is, when I try to edit multiple records. The script function only on the first record. How I can pass the for loop in php to javascript?
For Loop
$id=$_POST['checkbox'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
This gets all records depends on number of checkbox that have been checked. And when I get all the value in for loop opens records depends on counter value. Just like this how I can pass this for loop functions to javascript?
<script>
$('#sbtBtn').live('click',function(){
var textBox1=document.getElementById('pr_qty[]').value;
var textBox2=document.getElementById('pr_total').value;
if((+textBox2) > textBox1){
alert('value is greater than quantity');
return false;
}else{
}
});
</script>
<div class="container">
<form class="form-horizontal" action="" method="post">
<?php
$id=$_POST['checkbox'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$result1 = $mysqli->query("
SELECT a.item_name, a.item_description, a.counter, b.counter, b.pr, b.total_quantity
FROM app a
LEFT OUTER JOIN purchase_request b
ON a.counter=b.counter
WHERE a.counter='$id[$i]'
");
while ($row = $result1->fetch_assoc())
{ ?>
<div class="thumbnail">
<div style="display:none;">
<div class="control-label"></div>
<div class="controls">
<input name="counter[]" class="textbox" type="text" value="<?php echo $row['counter'] ?>" readonly="readonly"/>
</div>
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>Item</div>
<div class="controls" style='float:left;width:65%;margin-bottom:3px;'>
<input name="firstname[]" class="textbox" type="text" value="<?php echo $row['item_name'] ?>" readonly="readonly"/>
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>Description</div>
<div class="controls" style='float:left;width:65%;margin-bottom:3px;'>
<input name="lastname[]" class="textbox" type="text" value="<?php echo $row['item_description'] ?>" readonly="readonly"/>
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>PR Quantity</div>
<div class="controls" style='float:left;width:65%;margin-bottom:3px;'>
<input name="pr_qty[]" id="pr_qty[]" class="textbox" type="text" value="<?php echo $row['total_quantity']; ?>" />
<input id="pr_total" class="textbox" type="text" value="<?php $result2 = $mysqli->query("SELECT *, SUM(quantity) total_quantity FROM purchase_order WHERE counter='$id[$i]'");
while($rows = $result2->fetch_assoc()){ echo $rows['total_quantity']; }
?>">
</div>
<div class="control-label" style='float:left;width:25%;margin-left:10%;text-align:left;margin-bottom:3px;'>PR #</div>
<div class="controls">
<input name="pr[]" class="textbox" type="text" value="<?php echo $row['pr'] ?>" />
</div>
</div>
<br>
<?php
}
}
?>
<input name="submit" type="submit" id="sbtBtn" value="Update">
</form>
</div>
You can not give same id to multiple elements, you have to give unique id to your textboxes. In your function you getting textboxes byh Id, change it to class and also give separate classes to your textbox1 and 2. Otherwise your script will work on only first record.
js change
var textBox1=document.getElementsByClassName('tb1');
var textBox2=document.getElementsByClassName('tb2');
for(var i=0; i< textBox1.length; i++){
if((textBox2[i].value) > textBox1[i].value){
alert('value is greater than quantity');
return false;
}else{
}
}
and html change
<input name="pr_qty[]" id="pr_qty[]" class="textbox tb1" type="text" value="<?php echo $row['total_quantity']; ?>" />
<input id="pr_total" class="textbox tb2" type="text" value="<?php $result2 = $mysqli->query("SELECT *, SUM(quantity) total_quantity FROM purchase_order WHERE counter='$id[$i]'");
while($rows = $result2->fetch_assoc()){ echo $rows['total_quantity']; }
?>">
In your onclick event you can read input fields value like:
EDIT:
var val1 = $("input[name='UR_ELE1_NAME']").val();
var val2 = $("input[name='UR_ELE2_NAME']").val();
And you can compare like: if(val1 > val2){ .....}
I hope this helps.

Categories