How to remove elements inserted in the errorPlacement of jquery - javascript

I made a survey form with html, php and yii2. I have used the jquery validation plugin to check whether each question has an answer. Now the validation works and an error message pops up when a question is not answered.
I have also added a "br" tag to change line so that the error message will not be in the same row of the radio buttons. Now when I select an answer the error message disappears, but the "br" tag still exists. So how do I remove the "br" tag tag as well?
The following are my codes:
<?php
foreach ($questions as $question) {
?>
<label class="question"><?php echo $question->getTitle(); ?></label><br>
<?php
foreach ($choices as $choice) {
?>
<label class="radio-inline"><input type="radio" name="<?php echo $question->id . 'radio'; ?>"
value="<?php echo $choice->id; ?>"><?php echo $choice->getTitle(); ?></label>
<?php }
$this->registerJs('
rule[ "' . $question->id . 'radio"] = {
required: true,
}
', View::POS_BEGIN);
?>
<?php } ?>
<?php
$this->registerJs('
$(document).ready(function(){
$("#testForm").validate({
rules: rule,
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox" || element.attr("type") == "radio") {
error.insertAfter($(element).parents("label").prev($(".question")));
$("<br>").insertAfter($(element).parents("label").prev($(".question")));
}
else{
error.insertAfter(element);
}
}
});
});
',
View::POS_END);
?>

Related

PHP set dropdown value after page refresh

I'm having trouble setting the value of the dropdown after the form input refreshes the page. I can get the value but no matter what I try I'm unable to set the dropdown after the page refreshes. I've tried a number of different ideas I've found online too. I've tried both JavaScript and PHP solutions and all I can do is get the value but not set it. This is the code I have so far, which returns the drop down ID, I just need to know how to use it. I appreciate any help, thanks!
<?php
$pdo = new PDO('mysql:host=localhost; dbname=db', 'root', 'password')'
$sql = "SELECT divid, division FROM divisions ORDER BY division ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$divs = $stmt->fetchAll();
?>
<form method="post">
<select id="divi" name="divisions">
<?php foreach($divs as $div): ?>
<option value="<?= $div['divid'];?>"><?= $div['division']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['divisions'])){
$selected = $_POST['divisions'];
echo 'Selected: " . $selected;
} else {
echo 'Select division.';
}
}
?>
It's not very clear to me what you really want, however it looks like you want to select default:
<select id="divi" name="divisions">
<?php foreach($divs as $div): ?>
<option <?php echo ("mycondition ex: 'id == 1'") ? "selected" : NULL ?> value="<?= $div['divid'];?>"><?= $div['division']; ?></option>
<?php endforeach; ?>
</select>
You are simply missing any code that sets 'selected="selected"' in the HTML for the select field.
Also, your code is very hard to read so I've cleaned up the loop a little bit.
<form method="post">
<?php
echo '<select id="divid" name="divid">';
foreach ($divs as $div) {
$selected = '';
if (isset ($_POST['divid']) && ($_POST['divid'] == $div['divid'])) {
$selected = 'selected="selected"';
}
echo '<option value="' . $div['divid'] . '" ' . $selected . '>' . $div['division'] . '</option>';
}
echo '</select>';

Javascript is not applied on contents returned through ajax [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
Javascript: (Send data and will receive json content)
$('#member_group_dropDown').on('change', function () {
var inputData = {};
inputData.groupId = $(this).val();
if (inputData.groupId != "") {
$.post(myProp.base_url + 'folder/class/method', inputData, function (outputData) {
$('#selected_group').html(outputData.content);
$('#selected_group').html();
}, 'json');
}
$('#selected_group').html("");
});
PHP: (The content, which I will get it through ajax)
// assign buffering to variable then, send it for display
ob_start();
echo form_open(base_url('folder/class/method'), array('method' => 'post', 'id' => 'update_memberGroup_form'));
?>
<div class="group_title fontSize_20">
<span></span>
permissions<?php echo $memberGroups[0]['group_name']; ?>
</div>
<?php
foreach ($member_permissions as $permission) {
?>
<div class="container">
<label for="<?php echo $permission['name']; ?>" title="<?php echo $permission['description']; ?>"><?php echo $permission['title']; ?></label>
<?php if ($permission['input_type'] == 'radio'): ?>
<input type="radio" name="<?php echo $permission['name']; ?>" value="1"> <span class="fontSize_16">yes</span><input type="radio" name="<?php echo $permission['name']; ?>" value="0"><span class="fontSize_16">no</span>
<?php else: ?>
<input type="text" name="<?php echo $permission['name']; ?>" class="required" value="">
<?php endif; ?>
</div>
<?php
}
?>
<div>
<input type="submit" class="formButton3" value="edit">
</div>
</form>
<?php
$content = ob_get_contents();
ob_end_clean();
echo json_encode('content' => $content));
Now, when Apply an event on part of the content which I have received, as follow:
$('#update_memberGroup_form').on('submit', function () {
alert('hi');
return false;
});
it is not implemented.
Your handler is bound at run time - if the content is dynamically added either use event delegation, or bind the handler after appending:
$.post(myProp.base_url + 'folder/class/method', inputData, function (outputData) {
$('#selected_group').html(outputData.content);
$('#selected_group').html();
$('#update_memberGroup_form').on('submit', function () {
alert('hi');
return false;
});
}, 'json');

How to make HTML form fields automatically change when an option selected on a select field

Let's say I have a form like this in my CodeIgniter project.
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" name="S_happened">
<?php echo form_close(); ?>
What I want to do is if an user select one status, according to the it's type, show a text field to get an input.
I've made a way to get a type of the status like this: http://localhost/myapp/index.php/status/type/{status_id} where users can pass status ID and it will "echo" the type of the status.
I want to receive it back to the HTML page via a JavaScript method and show those text input fields. How do I do that?
Thank you. :)
As you have jQuery tag, so i suggest you this:
$('select').change(function(){
var inp = this.value.trim();
$(this).parent().find('input[type="text"][name^="'+inp+'"]').show().siblings(':text').hide();
});
I have posted the sample flow as per you want to do. hope this will helpful for you.
PHP:
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" id="E_happened" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" id="S_happened" name="S_happened">
<?php echo form_close(); ?>
JAVASCRIPT :
$('select').change(function(){
var statusId = $(this).val();
var statusType = $.get("http://localhost/myapp/index.php/status/type/"+statusId);
if(statusType == 'E')
{
$('#E_happened').value("what do you want here");
}
if(statusType == 'S')
{
$('#S_happened').value("what do you want here");
}
});

Hide div once sql query is successful

I am trying to make the div, "yourpick," hide once the POST query is successful. I know I'm checking for the POST in the middle of my form, but can we work around this. Thanks.
echo '<div class="yourpick" style="display:block;">
YOUR PICK:<br><form method="post" action="draft.php">';
echo '<input type="radio" name="pick" value="user1">User1<br>';
if(isset($_POST["pick"])){
$pick = $_POST["pick"];
$picksql = "UPDATE picks SET playerpick='" . $pick . "' WHERE id=$id AND picknum=$picknum";
if ($mysqli->query($picksql) === TRUE) {
echo "Pick Successful!";
echo "<script>document.getElementById('yourpick').style.display = 'none';</script>";
} else {
echo "Error Ocurred. Please contact commisioner.";
}
}
echo "<input type='submit' name='submit' /></form></div>";
It is best imo to use php alternative syntax in the HTML, so if isset($_POST["pick"]), then hide the div:
<?php if(isset($_POST["pick"])): ?>
<div class="yourpick" style="display:block;">
YOUR PICK:<br><form method="post" action="draft.php">
<input type="radio" name="pick" value="user1">User1<br>
<input type="submit" name="submit"></form></div>
<?php endif; ?>
Makes your code all nice and tidy. :)
You do not need Javascript for this:
if (isset($_POST["pick"])) {
$pick = $_POST["pick"];
$picksql = "UPDATE picks
SET playerpick = '$pick'
WHERE id = $id AND picknum = $picknum";
if ($mysqli->query($picksql) === TRUE) {
echo "Pick Successful!";
} else {
echo "Error Ocurred. Please contact commisioner.";
}
}
else {
echo '<div class="yourpick" style="display:block;">'.
'YOUR PICK:<br><form method="post" action="draft.php">'.
'<input type="radio" name="pick" value="user1">User1<br>'.
'<input type="submit" name="submit"></form></div>';
}
Sorry, but I'm not pointing out the obvious security risks of this code.

Change form label text at runtime

I have an HTML label and I would like to change its text at runtime. I know I can use innerHTML, which works, but why does it just just append my message in front of the already-set label text.
PHP:
<label for="hp_display" id="addToHP_<?php echo $x; ?>"></label><?php echo $addTo; ?>homepage: </label><input type="checkbox" id="hp_display_<?php echo $x; ?>" <?php echo $check; ?> onclick="addToHome('<?php echo md5($product['product_id']); ?>','<?php echo $add; ?>','<?php echo $x; ?>')" />
JAVASCRIPT:
function addToHome(id,a,n){
$.ajax({
url:'func/addToSlider.php',
type:'POST',
data:{type:a,id:id},
beforeSend: function(){
document.getElementById('addToHP_'+n).innerHTML = '';
document.getElementById('addToHP_'+n).innerHTML = 'Updating';
},
success:function(e){
if(e === '1'){
document.getElementById('addToHP_'+n).innerHTML = '';
if(a === 'remove'){
document.getElementById('addToHP_'+n).innerHTML = 'Add to homepage';
}else{
document.getElementById('addToHP_'+n).innerHTML = 'Remove from homepage';
}
}else{
alert('There has been a server changing your file, please try again');
}
}
});
}
It looks complicated, but surely innerHTML or JQuery's .html('') should replace the text instead of appending the text. I could just refresh page on success of the ajax but I think changing the label text is more user-friendly.
Your html markup is wrong, you have two closing label elements
<label for="hp_display" id="addToHP_<?php echo $x; ?>"></label><?php echo $addTo; ?>homepage: </label>
^^^^^^^^ ^^^^^^^
without all the php mark up it is
<label>X</label>Y</label>
You have too many </label>
<label for="hp_display" id="addToHP_<?php echo $x; ?>"></label><?php echo $addTo; ?>homepage: </label>
so while the label looks like it is being appended it is actually getting filled for the first time. remove the first </label> and problem solved.
should be:
<label for="hp_display" id="addToHP_<?php echo $x; ?>"><?php echo $addTo; ?>homepage: </label>

Categories