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

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('');
}
});
.....
});

Related

How to return second register form on submition?

I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.

How to hide an form after form is submitted

I am not that much good at programming. i am working on one feature, that is form hiding after the submit of form data. Here number of forms created dynamically. i need to hide the form once we submit the form data, to prevent multiple submission of form. here i used form inside div i also tried for div hiding. it is not working please let me know the solution.
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
function frmsubmit()
{
var frm = document.getElemetsByName('formdata')[0];
frm.submit();
frm.reset();
return false;
}
$('#submit_0').click(function() {
$.ajax({
url:"section.php?status=result",
data:$('#f_0').serialize(),
success:function(data)
{
alert(data);
$('#f_0')[0].reset();
}
});
});
// Haven written same code for submit_0 to submit_10
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Enter the values:</h3><br>
<ul class="nav nav-tabs">
<?php
foreach($clasarr as $temp)
{
?>
<li><a href="#<?php echo $temp; ?>"> <?php echo $temp; ?> </a </li>
<?php
}
?>
</ul>
<div class="tab-content">
<?php
$y=0;
foreach($clasarr as $temp)
{
?>
<div id="<?php echo $temp; ?>" class="tab-pane fade">
<form name="formdata" action="" method="post" class="form-horizontal" id="f_<?php echo $y; ?>">
<div class="col-md-offset-2 col-md-10">
<h3> CLASS: <?php echo $temp; ?></h3>
</div>
<input type="text" name="idr" id="idr" value="<?php echo $id; ?>" hidden>
<input type="text" name="clss" id="clss" value="<?php echo $temp; ?>" hidden>
<div class="form-group">
<label class="control-label col-sm-2" for="totalb">Budgeted #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="totalb" id="totalb" value="<?php echo $totalarr[$y]; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="received">Received #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="received" id="received_<?php echo $y; ?>" onblur="getcsv(<?php echo $y; ?>),getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="deleted"> Deleted data #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="deleted" id="deleted_<?php echo $y; ?>" onblur="getcsv(<?php echo $y; ?>),getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)"/ >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="csvno"> CSV Number #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="csvno" id="csvno_<?php echo $y; ?>" onload="getupload(<?php echo $y; ?>)">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="duplicate"> Duplicate #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="duplicate" id="duplicate_<?php echo $y; ?>" onblur="getupload(<?php echo $y; ?>),getexpected(<?php echo $y; ?>)" onclick="getupload(<?php echo $y; ?>)"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="upload"> Upload #:</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="upload" id="upload_<?php echo $y; ?>">
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-2">
<input class="btn btn-info" type="submit" name="submit" id="submit_<?php echo $y; ?>" value="submit" onclick="frmsubmit()">
<input class="btn btn-info" type="reset" name="Reset" value="Reset">
</div>
</div>
</form>
</div>
<?php
$y++;
}
You may not need both input type = "submit" and onclick event handler, the submit input will be enough.
Also there is a need to prevent default behaviour of the submit button since ajax is used to submit the form data.
Replace the input type "submit" with this
<input class="btn btn-info" type="submit" name="submit" id="someId" value="submit">
Also while dynamically creating the form use a class instead of id(presuming id is also dynamic so every new form creating will change the id)
<form name="formdata" action="" method="post" class="form-horizontal someFormClass"
id="someDynamicId">
// rest of the code
</form>
To prevent the default behaviour add event.preventDefault();.Inside the ajax success delegate the event of hiding the form from body
$('#submitButtonId').click(function(e) {
e.preventDefault();
var form = $(this).parents('form.someFormClass');
$.ajax({
//Rest of the code
success:function(){
$('body').find(form).hide()
}
})
});
Hopefully this pseudo code will be useful
A ridiculously simplified version of what you're trying to do. A form, in a div, with a jQuery on click hook that will hide the div on submit click.
$('#submit').click(function() {
$('#f_0').hide();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="f_0">
<form name="formdata" action="" method="post" class="form-horizontal" id="f_1">
<input class="btn btn-info" type="submit" name="submit" id="submit" value="submit">
<input class="btn btn-info" type="reset" name="Reset" value="Reset">
</form>
</div>
#AvinashT But is the ajax call being made or not?
#gurvinder372 ajax is called and form data is entring into table
successfully
Based on above discussion, you just need to add this line in the success handler to hide the form
$('#submit_0').closest( "form" ).hide()
Here number of forms created dynamically. i need to hide the form once
we submit the form data, to prevent multiple submission of form.
Form is being submitted multiple times, because you have two handlers (one is via onclick and other via submit click event handler).
You need to remove the onclick="frmsubmit()" from the form tag since submit click event handler is already taking care of form-submission.

Text not carrying over to POST variable

Here is the HTML: Line 18 below is not carrying over to $_POST['storename'] after Submit is hit. All other text fields are carrying over just fine. The only difference is that this autofills with data from database using PHP and AJAX. I've attached all coding in reference to that field.
Here's the link to the site: http://drmwebdesign.com/project002/product-insert.php
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="text" name="pname" id="pname" value="<?php echo $pname;?>" placeholder="Product Name" />
</div>
<div class="6u 12u(mobilep)">
<input type="text" name="brand" id="brand" value="<?php echo $brand;?>" placeholder="Product Brand" />
</div>
<div class="6u 12u(mobilep)">
<input type="text" name="price" id="price" value="<?php echo $price;?>" placeholder="Product Price" />
</div>
<div class="6u 12u(mobilep)">
<input type="text" name="upc" id="upc" value="<?php echo $upc;?>" placeholder="Product UPC" />
</div>
</div>
<div class="row uniform">
<div class="12u">
<input type="text" name="storename" id="storename" class="form-control" placeholder="Enter Store Name" />
<div id="storeList"></div>
</div>
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" value="Submit Product" /></li>
</ul>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$('#storename').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"php/storelist.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#storeList').fadeIn();
$('#storeList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#storename').val($(this).text());
$('#storeList').fadeOut();
});
});
</script>
Try the following :
1) Use the chrome network to check the request / response
2) If the field contains a long data check the max post size
3) If the field is a list, and you are selecting multiple choices you need to check this question
4) check if multiple fields have the same name/id
$(document).on('click', 'li', function(){
$('#storename').val($(this).text());
$('#storeList').fadeOut();
});
Triggers when you press the submit button, setting #storename value to nothing.
Add a class to the store names and target onclick using that.

Ajax callback only applying to top div in list of jquery form groups

Hello smarter people,
So as the title conveys, i'm having some difficulties, and I've wasted a good 8 hours trying to figure it out :)
I posted a Question earlier, to which I got no answers. I was having difficulties with my ajax, and it's interaction with a form. This form is in an admin panel, and is for dynamically creating and editing navigation links on the front end of my (hopefully) soon-too-be site.
My problem specifically is: I am unable to, via ajax, have the text-content of the anchor tag (which causes the form to dropdown), to immediately reflect on screen...
http://i1379.photobucket.com/albums/ah126/conchairtoe/3_zpsb897a6a4.png
As you can see, the ajax has run, no errors, yet the label (anchor tag for enacting drop-down form) remains "test", when I typed "testing!!!!!!" in.
Everything behind the scenes worked, as the database successfully updates the corresponding data, and so does the anchor tag text once i reload the page, but that ain't very ajaxy now is it!
Here's the Javascript for when the form is submitted.
// NAV ITEM FORM - UPDATE / SUBMIT
$(".nav-form").submit(function(event) {
var navData = $(this).serializeArray(); // The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.
var navLabel = $('input[name=label]').val();
var navID = $('input[name=id]').val();
$.ajax({
url: "ajax/navigation.php",
type: "POST",
data: navData
}).done(function(){
$("#label_"+navID).html(navLabel);
}); // END $.ajax
alert("navID = "+navID+" navLabel = "+navLabel);
event.preventDefault(); // will prevent form from submitting
});//END nav-form
Please note the .done callback.
I've narrowed the problem down!
The ajax works ONLY on whichever of the sortable anchors is in position 1 (the top of the list) - for when I change the "Home Page", or, again, which ever one I happen to move to the top of the list, the label updates immediately as per the ajax.
As you can see in the code, I have those alerts to verify this:
http://i1379.photobucket.com/albums/ah126/conchairtoe/final_zps7a7ddc68.png
Here is the code for the DOM environment
Navigation
<div class="row">
<div class="col-md-3">
<ul id="sort-nav" class="list-group-item">
<!--EXISTING NAV-ITEMS-->
<?php
$query = "SELECT * FROM navigation ORDER BY position ASC";
$result = mysqli_query($dbc, $query);
while ($list = mysqli_fetch_assoc($result)) { ?>
<li id="list_<?php echo $list['id']; ?>" class="list-group-item">
<a id="label_<?php echo $list['id']; ?>" data-toggle="collapse" data-target="#form_<?php echo $list['id']; ?>">
<?php echo $list['label']; ?> <i class="fa fa-chevron-down"></i>
</a>
<div id="form_<?php echo $list['id']; ?>" class="collapse">
<!--FORM-->
<form class="form-horizontal nav-form" role="form" action="index.php?page=navigation&id=<?php echo $list['id']; ?>" method="post">
<!-- ID -->
<div class="form-group">
<label class="col-sm-2 control-label" for="id">ID</label>
<div class="col-sm-10">
<input type="text" class="form-control input-sm" value="<?php echo $list['id'];?>" name="id" id="id" placeholder="ID - name" />
</div>
</div>
<!-- LABEL -->
<div class="form-group">
<label class="col-sm-2 control-label" for="label">Label</label>
<div class="col-sm-10">
<input type="text" class="form-control input-sm" value="<?php echo $list['label'];?>" name="label" id="label" placeholder="Label" />
</div>
</div>
<!--URL -->
<div class="form-group">
<label class="col-sm-2 control-label" for="value">URL</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['url'];?>" name="url" id="url" placeholder="URL"></input>
</div>
</div>
<!--POSITION -->
<div class="form-group">
<label class="col-sm-2 control-label" for="value">Position</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['position'];?>" name="position" id="position" placeholder="Position"></input>
</div>
</div>
<!-- STATUS -->
<div class="form-group">
<label class="col-sm-2 control-label" for="status">Status</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['status'];?>" name="status" id="status" placeholder=""></input>
</div>
</div>
<!--Button and Hidden Input-->
<button type="submit" class="btn-btn-default">Save</button>
<input type="hidden" name="submitted" value="1" />
<input type="hidden" name="opened_id" value="<?php echo $list['id']; ?>" />
<span class="pull-right">
<a id="del_<?php echo $list['id']; ?>" class="btn btn-danger nav-item-delete" href="#" style="margin-bottom: 2px;" title="delete nav item"><i class="fa fa-trash"/></i></a>
</span>
</form> <!--END form-->
</div>
</li>
<?php } ?>
</ul>
</div>
<div class="col-md-9">
<div id="callback"><?php if(isset($message)) { echo $message; } ?></div>
</div> <!-- END col-md-12 -->
So yea, I truly apologize for my ignorance. Bare in mind that I barely could grasp css just 2 months ago or so.
THANK YOU SO MUCH FOR YOUR HELP IF YOU CAN PROVIDE IT.
Because you are not looking at the current form for the navID. The code $('input[name=id]') is using the first element it finds. You need to look at the form, use find().
var form = $(this);
var navData = form.serializeArray();
var navLabel = form.find('input[name=label]').val();
var navID = form.find('input[name=id]').val();

jQuery - best way to add/remove form section dynamically

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>

Categories