Get Php variable in to Javascript function - javascript

I know this topic is frequently asked but I've tried many ways and nothing works for me. I have a lot of checkboxes with the id generated (in Php) by a variable like this:<input type="checkbox" id="<?php echo $id; ?>" >. That I want to do is call a Javascript function every time that a radiobutton (autogenerated) is clicked for that that checkbox with id="<?php echo $id; ?>"can be checked.
I tried with things like:
function check() {
var id = '<?php echo $id; ?>';
document.getElementById(id).checked = true;
}
I know that maybe I could do with Ajax but I don't know how.
(Up to this point is obvious that you know that the radiobutton has onclick = "check ()").
If anyone can tell me what I can do is I appreciate a lot.

You can try something like this:
<input type="checkbox" id="checkbox-<?php echo $id; ?>" />
<input type="radio" data-check="checkbox-<?php echo $id; ?>" onclick="check(this)" />
<script>
function check(e)
{
document.getElementById(e.getAttribute('data-check')).checked = true;
}
</script>

You can use below code for dynamically generated radio and checkbox
$("input[type='radio']").click(function() {
$(this).closest('input[type="checkbox"]').prop('checked', true);
});

Related

Unable to get button value with loop Jquery

I am working with jquery and PHP,I want to display "buttons" according to database value(dynamic) and want to get button values in jquery, I am using "input type hidden", But right now getting value="1"(static), But I want to get "correct" value (if I select button 2 then 2 value should get in jquery)
Here is my HTML code
<?php $j=$records['start_range'];
$max= $records['end_range'];
for($i=$j;$i<=$max; $i++) { ?>
<button class="btn btn-scale btn-scale-asc-<?php echo $i; ?>">
<?php echo $i; ?>
<input type="hidden" <?php if($records['IsRatingQuestion']=="" || empty($records['IsRatingQuestion'])){ ?>name='ques_<?php echo $records['ques_id']; ?>' <?php } else{ ?>name='rangeR_<?php echo $records['ques_id']; ?>' <?php } ?> id="ratings" value="<?php echo $i; ?>">
</button>
<?php } ?>
Here is the script, Where I am wrong?
<script>
$(document).ready(function(){
$("#next1").click(function(){
var rating =$("#ratings").val();
alert(rating);
});
});
</script>
Before anything else, you need to remove input from inside that button. It's not a valid HTML.
Moreover, as mentioned in the comments, you cannot have the same id for all inputs, so I'd just remove it.
How about something like this:
$(document).ready(function() {
$('.item').each(function() {
var $button = $(this).find('button')
var $input = $(this).find('input')
$button.click(function() {
alert($input.val())
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<button>1</button>
<input type="hidden" value="1">
</div>
<div class="item">
<button>2</button>
<input type="hidden" value="2">
</div>
<div class="item">
<button>3</button>
<input type="hidden" value="3">
</div>
<div class="item">
<button>4</button>
<input type="hidden" value="4">
</div>
As far as I am understanding, you just want to show the value of the dynamic button using jquery. For this you just need to pass the value to the button using data attribute and then you can get the value using jquery.
<?php $j=$records['start_range'];
$max= $records['end_range'];
for($i=$j;$i<=$max; $i++) {
echo '<button class="get-value" data-value="'.$i.'">Button '.$i.'</button>';
} ?>
<input type="text" id="show-value">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.get-value', function(){
var button_value = $(this).data('value');
$('#show-value').val(button_value)
});
});
</script>
I don't think putting an <input> inside of a <button> is valid html (although it seems to work?). Instead you can just assign those values as attributes of the button itself. Also ids have to be unique, so if you have a bunch of buttons with the same id, that is also invalid. I tend to stay away from ids and just use classes to avoid this.
Also, rather than having a bunch of choppy php, you can build a single string of html and echo it back all at once. By using double qoutes " on the outside of a string, you can use single quotes ' on the inside and drop variables right into the string without escaping or concatenating anything. Although you have to wrap associative arrays in brackets {} for it to parse correctly. PHP strings.
I'm guessing $name isn't a static variable, but without seeing the rest of your code, this is just an example:
<?php
$html = "";
$name = ($records["IsRatingQuestion"] == "" || empty($records["IsRatingQuestion"])) ?
"ques_{$records["ques_id"]}" :
"rangeR_{$records["ques_id"]}";
for($i = $records["start_range"]; $i <= $records["end_range"]; $i++) {
$html .= "<button class='btn btn-scale btn-scale-asc-$i ratings' name='$name'>$i</button>";
}
echo $html;
?>
$('.btn.ratings').on('click', function() {
//$(this).text() = $i
//$(this).attr('name') = $name
});

How to submit LOTS of buttons

I'm displaying rows of data from a mysql database, and on each row I have three icons that I'd like to function as buttons. When an icon is clicked, I'd like to send the user to another page, and send that page both which icon was clicked and what row it was on. Here's some sample code:
<form action="nextpage.php" method="POST">
while ($row = $result->fetch_assoc))
{
echo '<input type="image" src="button1.png" name="button1">';
echo '<input type="image" src="button2.png" name="button2">';
echo '<input type="image" src="button3.png" name="button3">';
echo $row["cName"], '<br/>', PHP_EOL;
}
</form>
I've tried adding a value field for each input icon, but that didn't seem to work. I've tried putting the row identifier in the input's name, but it came out with changed characters, making it difficult to extract.
This page will likely display up to a hundred rows from the database, so aside from creating a separate form for each icon on each row (300 forms), what's the best way to go about this?
If you can use jquery, here is how I would approach it:
<form action="nextpage.php" method="POST">
<input type="hidden" id="hidden-icon" name="icon" value="" />
<input type="hidden" id="hidden-row" name="row" value="" />
</form>
<?php
$row_num = 0;
while ($row = $result->fetch_assoc))
{
echo '<img src="button1.png" />';
echo '<img src="button2.png" />';
echo '<img src="button3.png" />';
echo $row["cName"], '<br/>', PHP_EOL;
$row_num++;
}
?>
<script type="text/javascript">
$('.click-register').on('click', function (e) {
//Stop the link from jumping to the top of the page
e.preventDefault();
//Fill in the hidden form values
$('#hidden-icon').val($(e.target).data('icon'));
$('#hidden-row').val($(e.target).data('row'));
//Submit the form
$('form').submit();
});
</script>
That code is off the top of my head and untested, but here's the general idea:
First, move the icons outside of the form, as this approach doesn't require them to be inputs any longer;
Since the icons don't need to be inputs, we make them images inside of anchors;
We put the data we need on the anchors (data-icon and data-row);
Using jquery (in this case, you could do this pure javascript if you needed to), we:
Listen for any clicks of the anchors;
Grab the data from the clicked link and fill in our hidden form fields; and
Submit the form
Again, I used jquery because it's common and familiar to many. You can accomplish this with many other javascript frameworks or even pure javascript if that was desireable. Conceptually though I think it is sound.
If you don't want to go with javascript, the option of using links instead of POST'ing with a form is potentially viable.
Here's what that might look like:
<?php
$row_num = 0;
while ($row = $result->fetch_assoc))
{
echo '<img src="button1.png" />';
echo '<img src="button2.png" />';
echo '<img src="button3.png" />';
echo $row["cName"], '<br/>', PHP_EOL;
$row_num++;
}
?>
Hope that helps!
Based on the comment by mcgraphix, I eliminated the form entirely and changed all the input to links and appended the button id and row id to each link, as shown below:
while ($row = $result->fetch_assoc))
{
echo '<img src="button1.png">';
echo '<img src="button2.png">';
echo '<img src="button3.png">';
echo $row["cName"], '<br/>', PHP_EOL;
}
Thanks, mcgraphix! :)
PS - As this posted, I saw basically the same answer by xjstratedgebx, so thank you as well!
This might seem a bit of a strange idea but you can just use submit buttons for each button and then style the image over top of the button. The good thing about submit buttons is that only the button that is pressed is sent through the request, so effectively you only need one form for the whole page, and a unique name for each button.
<form action="nextpage.php" method="POST">
while ($row = $result->fetch_assoc))
{
echo '<button class="img-button b1" name="$row["cName"]button1" />';
echo '<button class="img-button b2" name="$row["cName"]button2" />';
echo '<button class="img-button b3" name="$row["cName"]button3" />';
echo $row["cName"], '<br/>', PHP_EOL;
}
</form>
I don't know PhP so not sure if that compiles, but hopefully you get the idea that as long as the buttons have unique names, only one name will be sent through the request.
Then in your style sheet something like the following (not tested):
.img-button {
height: 20px;
width: 20px;
}
.button1 {background-image: url('button1.png');}
.button2 {background-image: url('button2.png');}
.button1 {background-image: url('button2.png');}
Hope that is useful!

Search Button Broken on Magento

First off, I am not a developer. We don't have a dedicated developer for our Magento website. A few days ago my boss asked me to fix an error on the website. What is happening is the search button doesn't work. I try to click it and nothing happens. When I go into Inspect Element, there is an error in the console. It says "Uncaught TypeError: Cannot read property 'get' of undefined" in prototype.js:5557.
I have tried everything I can think of to fix it. Which to be honest isn't a lot. I've reindexed files, cleared the cache, updated Magento, and made sure the button is located where its supposed to be. I've made sure products are searchable within Magento and I have made sure the search type is set to like/fulltext. I think its probably an error in the code, but I have no idea what to edit or where. I am going mad trying to figure this out.
The link to the store is: http://store.excitementvideo.net/ But please keep in mind it is NSFW.
Thank you
Update: I've been told its a form error? Here is my form.mini.phtml file
<form id="search_mini_form" action="<?php echo $this->helper('catalogsearch')->getResultUrl() ?>" method="get">
<div class="form-search">
<label for="search"><?php echo $this->__('Search:') ?></label>
<form> <input id="search" type="text" name="<?php echo $this->helper('catalogsearch')->getQueryParamName() ?>" value="<?php echo $this->helper('catalogsearch')->getEscapedQueryText() ?>" class="input-text" /></form>
<form><button type="submit" title="<?php echo $this->__('Search') ?>" class="button"><span><span><?php echo $this->__('Search') ?></span></span></button></form>
<div id="search_autocomplete" class="search-autocomplete"></div>
<script type="text/javascript">
//<![CDATA[
var searchForm = new Varien.searchForm('search_mini_form', 'search', '<?php echo $this->__('Search entire store here...') ?>');
searchForm.initAutocomplete('<?php echo $this->helper('catalogsearch')->getSuggestUrl() ?>', 'search_autocomplete');
//]]>
</script>
</div>
</form>
Looks like the javascript has slight bug with the string part.
try changing
<script type="text/javascript">
//<![CDATA[
var searchForm = new Varien.searchForm('search_mini_form', 'search', '<?php echo $this->__('Search entire store here...') ?>');
searchForm.initAutocomplete('<?php echo $this->helper('catalogsearch')->getSuggestUrl() ?>', 'search_autocomplete');
//]]>
</script>
to
<script type="text/javascript">
//<![CDATA[
var searchForm = new Varien.searchForm('search_mini_form', 'search', '<?php echo $this->__("Search entire store here...") ?>');
searchForm.initAutocomplete('<?php echo $this->helper("catalogsearch")->getSuggestUrl() ?>', 'search_autocomplete');
//]]>
</script>

How to submit one form out of multiple with javascript

On my website I have a big list of all the letters people can view.
For every letter there is a form which sends some data from the letter to the next page. What I want to do is to submit the form with a link, and not with a button.
As far as I know, that is not possible with PHP. So i tried making what i want in Javascript.
My programming experience in Javascript is litterly 0%. I need some help with this :)
This is the code I'm using:
<script type="text/javascript">
function submitform()
{
document.forms["brief_weergeven"].submit();
}
</script>
<form id='brief_weergeven[]' action='<?php echo $main; ?>beveiligd/achterbanner/nieuwsbrief.php' method='POST'>
<input type='hidden' name='nummer' value='<?php echo $brieven[0]; ?>'>
<input type='hidden' name='datum_maand' value='<?php echo $maand_getal; ?>'>
<input type='hidden' name='datum_jaar' value='<?php echo $jaar; ?>'>
<a href="javascript: submitform()" class='button'>Nieuwsbrief <?php echo $brieven[0]; ?> (<?php echo $maand .' ' .$jaar; ?>)<BR></a>
</form>
This code runs for every letter. As you can see, I'm using a array to give all the forms a seperate ID. The only thing is that i have no idea how to let javascript know which forum i submitted.
How can I do this? Please remember that i know nothing about javascript, so please explain what you're doing in your answer.
You dont need javascript to do this, just use css to make your button look like a link:
Css:
button {
border:none;
padding:0;
background: none;
color: blue;
text-decoration: underline;
cursor: pointer;
}
html:
<button type="submit">Submit</button>
You can usedocument.getElementById('form-id')
And event handler like this
var form = document.getElementById('your-form-id');
form.onsubmit = function(){
// code
}
user574632 gave you a nice alternative. Still even want to use JavaScript you can try below.
Use the jQuery onclick method having the id attribute of the link as selector.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#submit_link").on("click", function(){
var form = $(this);
var url = form.attr("action");
var data = form.serialize();
$.post(url, data);
});
});
</script>
<form id='brief_weergeven[]' action='<?php echo $main; ?>beveiligd/achterbanner/nieuwsbrief.php' method='POST'>
<input type='hidden' name='nummer' value='<?php echo $brieven[0]; ?>'>
<input type='hidden' name='datum_maand' value='<?php echo $maand_getal; ?>'>
<input type='hidden' name='datum_jaar' value='<?php echo $jaar; ?>'>
<a href="#" id="submit_link" class='button'>Nieuwsbrief <?php echo $brieven[0]; ?> (<?php echo $maand .' ' .$jaar; ?>)<BR></a>
</form>

Disabling a submit button after one click without sacrificing the functionality of the form

I have asked this question before but no one was able to give a satisfactory answer.
I have a quiz website which has four radio buttons for the four options. When the user clicks on the submit button, a PHP script executes which check whether the answer is correct or not.
What I need to do is to disable the submit button after it is pressed once. All the answers that I received in my previous question interfered with the functionality of my form (it was not getting submitted). Please give a solution which do not sacrifices the functionality of the form.
Also,if you give a Javascript code as your answer, please do help me in implementing that as I am naive in Javascript.
Here is my code:
<form action="programming_skills.php?ad=<?php echo $a; ?>" method="post" id="quizsubmit">
<tr align="center">
<?php echo $row['q_desc']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans1']; ?>" <?php echo ($_POST['ans'] == $row['ans1'] ? 'checked' : '') ?>/>
<?php echo $row['ans1']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans2']; ?>" <?php echo ($_POST['ans'] == $row['ans2'] ? 'checked' : '') ?>/>
<?php echo $row['ans2']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans3']; ?>" <?php echo ($_POST['ans'] == $row['ans3'] ? 'checked' : '') ?>/>
<?php echo $row['ans3']; ?><br />
<input type="radio" name="ans" value="<?php echo $row['ans4']; ?>" <?php echo ($_POST['ans'] == $row['ans4'] ? 'checked' : '') ?>/>
<?php echo $row['ans4']; ?><br />
<tr><td><input type="submit" id="sub" value=Submit_Answer></td></tr></form></table><table border="1" align="center">
<?php
if(isset($_POST['sub']))
{
$a_value=$a;
$answer=$_POST['ans'];
$q2="select * from question where q_id=$a_value";
$r2=mysql_query($q2);
if ($row=mysql_fetch_array($r2))
$trueans=$row['true_ans'];
if ($answer==$trueans)
{
$userid=$_SESSION['user_email'];
$q1="select * from temp_score WHERE user_id='$userid'";
$rw=mysql_query($q1);
while($row=mysql_fetch_assoc($rw))
$score=$row['temp_score'];
$score=++$score;
$z="update temp_score set temp_score='$score' where user_id='$userid'";
mysql_query($z);
?>
Your answer is correct. <?php $a=++$a; ?>
Click Here for next question
<?php
}
else
{
?>Your answer is wrong. The correct answer is <i>'<?php echo $trueans; ?>'</i>.<br />
<?php $a=++$a; ?>
Click Here for next question
<?php }
}
++$a;
$a=++$a;
}
}
}
else
{
echo '<meta http-equiv="refresh" content="0; url=results.php">';
}
?>
Hi found a fiddle which might help u to prevent default click event below code is will help...
document.getElementsById("quizsubmit").onclick = function () {
this.disabled = true;
};
http://jsfiddle.net/zb8CZ/
Disable it after a timeout:
<input type="submit" id="sub" value=Submit_Answer onclick="setTimeout('document.getElementById(\"sub\").disabled=!0;',100);">
You can either use an onclick event on the submit button like this:
onclick="this.disabled='disabled';this.form.submit();"
Thus, the form gets submitted via JS.
Or better make use of the onsubmit event on the form element:
onsubmit="document.getElementById('submit_button').disabled = 'disabled';"
"submit_button" is the ID attribute of your button in this case.

Categories

Resources