Change form label text at runtime - javascript

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>

Related

How to remove elements inserted in the errorPlacement of jquery

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);
?>

How to continue two type of loop at a time using Javascript and PHP

I need one help.i need to continue 2 types of loop at a time using Javascript and PHP.Let me to explain my code and scenario as well.
<script>
function addQuestionField(){
var get =$("#ques").val();
if(get==null || get==''){
alert('Please add no of questions');
}else{
var counter = 0;
if (counter > 0){
return;
}else{
counter++;
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
for(var i=1;i<get;i++){
$('#container').append(' <textarea class="form-control" name="questions'+ i +'" id="questions" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea>');
<?php
foreach($feeddata as $v){
?>
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>');
<?php
}
?>
}
}
}
}
</script>
Here i have one for loop but inside this one foreach loop is still there .By doing this in one iteration of for loop foreach loop continuing many times which i dont need.Here i need each time of for loop the foreach loop also iterate.suppose for 1st iteration of for loop the foreach loop also iterate once and so on.Please help me.
Use current and next functions to get consistent elements of an array. So, this fragment of your code
foreach($feeddata as $v){
?>
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>');
<?php
}
?>
should be changed to
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo current($feeddata)['_id']; ?>"> <?php echo current($feeddata)['answertype']; ?>');
<?php next($feeddata); ?>
or, if you use old version of php do it in such way:
<?php $v = current($feeddata); ?>
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>');
<?php next($feeddata); ?>

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.

Issue with query and javascript variable

I know this will require the use of AJAX but I don't know where to start with it.
<td class="dataTableContent" valign="top">
<div>
<input id="<?php echo " update_products[ " . $orders_products_id . "] [backorder_date] "; ?>" name="<?php echo " update_products[ " .
$orders_products_id . "][backorder_date] "; ?>" size="10" ?>onChange="backorderDate('
<?php echo $orders_products_id; ?>')" value='
<?php echo tep_date_short($order->products[$i]['backorder_date']); ?>'>
</div>
</td>
So what I have here is an input box that requires users to input a back order date if there is one for their product. Now if you notice I have an event that activates a function onChange for this input box.
function backorderDate(pid)
{
<?php
$prod_id = "<script language='JavaScript'>pid;</script>";
echo $prod_id;
$query_send = tep_db_query("SELECT backorder_date from pos_products WHERE
orders_products_id= '$prod_id' ORDER BY backorder_date DESC");
$final = tep_db_fetch_array($query_send);
?>
alert("There has been a change to the Back Order Date and this may
change the In Stock checkbox.");
alert("<?php echo $final; ?>");
}
Then as you can see above this is the function that is being called. I pass the variable from the input box to the function and I named it 'pid'. Then here is where the problem begins. I need that variable's content in order to call the correct info in a query. Clearly what I have there is wrong and it most likely needs AJAX. Can anyone push me in the right direction?
I'm not a PHP wiz, but I'm guessing that the PHP in your JS function gets parsed and doesn't exist when the function is actually run. Therefore, the script tag is unnecessary.
function backorderDate(pid) {
<?php echo $prod_id ?> = pid;
You can't do SQL from javascript like this. It's not only impossible, it's a huge security risk. Assuming the PHP outputs the input correctly, change your javascript function to look something like this:
function backorderDate(pid)
{
$.ajax ({
url: "backend.php",
data: pid,
success: function(data) {
///do whataever you want here
}
})
}
Then create a PHP file called backend.php where you do your query, process the results, and send back data to your jQuery function.
EDIT:
Looking over this again, I'm not sure what you're trying to do here:
<input id="<?php echo " update_products[ " . $orders_products_id . "] [backorder_date] "; ?>" name="<?php echo " update_products[ " .
$orders_products_id . "][backorder_date] "; ?>" size="10" ?>onChange="backorderDate('
<?php echo $orders_products_id; ?>')" value='
<?php echo tep_date_short($order->products[$i]['backorder_date']); ?>'>
You may mean something like this? :
<input id="<?php echo $update_products[orders_products_id][backorder_date]; ?>"
name="<?php echo $update_products[orders_products_id][backorder_date]; ?>"
size="10"
onChange="backorderDate('<?php echo $orders_products_id; ?>')"
value='<?php echo tep_date_short($order->products[$i]['backorder_date']); ?>'>
Without seeing more of your code, I can't really decipher where all these variables are coming from.

jQuery set attribute onclick all elements instead of using inline JS

I have some inline JS that I'm having trouble changing over to jQuery. I would like to remove all the inline onclick events and target them all by class.
HTML - checkbox
<td class="center">
<?php if ($product['selected']) { ?>
<input type="checkbox" name="selected[]" id="<?php echo $product['product_id']; ?>_select" value="<?php echo $product['product_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" id="<?php echo $product['product_id']; ?>_select" value="<?php echo $product['product_id']; ?>" />
<?php } ?>
</td>
HTML - inline JS
<input type="text" class="editable" name="<?php echo $product['product_id']; ?>_model" id="<?php echo $product['product_id']; ?>_model" value="<?php echo $product['model']; ?>" size="16" onclick='document.getElementById("<?php echo $product['product_id']; ?>_select").setAttribute("checked","checked");' />
The above code works but when I try to use jQueryversion 1.7.1 it breaks. Here is the code I have tried.
$(document).ready(function() {
$(".editable").live("click", function() {
$("#<?php echo $product['product_id']; ?>_select").attr("checked", "checked");
$("#<?php echo $product['product_id']; ?>_select").checked = true;
});
});
I'm not really familiar with jQuery but I think it's close. Any Ideas?
EDIT:
The problem is with the $("#<?php echo $product['product_id']; ?>_select") it works if hard coded. KevinB was correct even though ive never had this problem before but never used it within here $(element)
.live was deprecated in version 1.7 -- probably explains it. Use .on instead.
$(".editable").on("click", function() {
var name = '<?php echo $product['product_id']; ?>';
console.log("Name: " + name);
var el = $("#" + name + "_select");
console.log(el);
el.prop("checked", "checked");
});

Categories