Unable to get button value with loop Jquery - javascript

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

Related

Getting input value that has its own iterated button upon click

I've successfully added an iterator to my php foreach loop so that I can create a unique button for each row in my table.
<?php $i = 1;?>
#foreach($getPromoCodes as $codes)
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}">
<?php $i++;?>
#endforeach
However, I can't figure out, once the button is pressed, how to get the value of the input from the clicked button. This being due to the uniqueness of each button with the iterator.
var promo_codet_id = document.getElementsByClassName("promo_code_id");
This returns undefined when I console log it.
How do I need to change my JS for this?
You can do this way:
<div class="elements">
<?php $i = 1;?>
<?php foreach($getPromoCodes as $codes): ?>
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}">
Link
<?php $i++;?>
<?php endforeach; ?>
</div>
jquery:
$('.elements').on('click', '.btn', function(e){
e.preventDefault();
console.log($(this).data('id'));
});
You can use this.value in a call to a javascript function:
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}" onclick="doSomething(this.value); return false;">

Appended element goes undefined when being passed over

Hi i have this code where everclick appends a DOM element where the user can pick what he wants then submits it to another page.
<form action="view.php" method="post">
<textarea name="paragraph[]"></textarea><input type="button" onclick="addparagraph();" value="+">
</input>
<select name="font[]">
<option>Tohoma</option>
<option>Arial</option>
</select>
<div id="firstpart"></div>
<input type="submit" value="submit"/>
</form>
<script>
function addparagraph(){
var string = '<textarea name="paragraph[]"></textarea>'+
'<select name="font[]"><option>Tohoma</option><option>Arial</option></select>';
jQuery('#firstpart').append(string);
}
</script>
once submitted it does not get the value of the appended elements
here is the view.php part
foreach($_POST['paragraph'] as $count => $value){
echo "$value";
echo "$_POST['font'][$count];
}
it appends the elements but it does not display the values of the appended array.. it gives an error offset undefined
1.You need to add a jQuery library to make your code to work.
2.You need to change PHP code too.
The code needs to be like below:-
HTML PAGE:-
<form action="view.php" method="post">
<textarea name="paragraph[]"></textarea><input type="button" onclick="addparagraph();" value="+"></input>
<select name="font[]">
<option>Tohoma</option>
<option>Arial</option>
</select>
<div id="firstpart"></div>
<input type="submit" value="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function addparagraph(){
var string = '<textarea name="paragraph[]"></textarea>'+'<select name="font[]"><option>Tohoma</option><option>Arial</option></select>';
jQuery('#firstpart').append(string);
}
</script>
PHP PAGE:-
<?php
foreach($_POST['paragraph'] as $key => $value){
echo $value;
echo "<br>";
echo $_POST['font'][$key];
}
Your loop should look like this:
foreach($_POST['paragraph'] as $count => $value){
echo $value;
echo $_POST['font'][$count];
}

Hide textbox if empty

I want to make this code hidden if value is null,
so if the value is empty, remove this div.
div
<?php echo "test" ?>
<input type="text" id="textfield" name"test" value="<?php echo $design_value; ?>" />
div
I can fill value with PHP so when my site load value is null.
so I need any javascript code that can hide this div if no text on a textbox.
So please try to find any simple code. You can use Javascript or jQuery or whatever you think is better for this.
get Textbox value , Check if it empty then remove div.
var getTextVal= $('#textfield').val();
if(getTextVal == ""){
$('#textfield').closest('div').remove();
}
You can use JQuery $(document).ready. This event is fired after all elements in the page have initialized and recieved their values:
$(document).ready(function() {
if ($("#textfield").val == '')
$("#textfield").hide();
});
if value == '' then hide input field by adding display property to none of that element.
You can do that by running simple javascript code as shown below,
<div id="hide">
<?php echo "test" ?>
<input type="text" name="test" id="textfield" value="<?php echo $design_value; ?>" />
</div>
<script>
var hide = document.getElementById("hide");
var input = document.getElementById("textfield")
if(input.value == ""){
hide.style.display = "none";
}
</script>
You can do it by php (it won't show any output):
<?php if ($design_value != null) { ?>
<input type="text" id="textfield" name"test" value="<?php echo $design_value; ?>" />
<?php } ?>
Or in this way (a hidden field):
<input type="<?php echo ($design_value != null) ? 'text' : 'hidden'; ?>" id="textfield" name"test" value="<?php echo $design_value; ?>"/>
In plain JavaScript:
var textField = document.getElementById('textfield');
var text = textField.value;
textField.parentNode.style.display = (text) ? 'block' : 'none';

How can I reloaded URL link, that it stay the same after I click on submit button

I have simple form:
<div class="form-style-2">
<form action="" name="formular" id="formular" method="GET">
<label for="actual_position"><span>From: <span class="required"></span></span><input name="actual_position" type="text" maxlength="512" id="actual_position" class="searchField"
<?php if(!empty($actual_position)){ ?>
value="<?php echo $_GET['actual_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<label for="final_position"><span>To: <span class="required"></span></span><input name="final_position" type="text" maxlength="512" id="final_position" class="searchField" <?php if(!empty($final_position)){ ?>
value="<?php echo $_GET['final_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<input type="submit" value="Find path" />
And another multiselect in form who gets values form url link and compere with database and get som results. Here is a code:
<table width= "570px">
<tr><td width="200px" style="align:center"><b>Waypoints:</b> <br>
<tr><td width="370px"><select style="float:center; margin-left:5px" multiple id="waypoints">
if(!empty($urls)){
foreach($urls as $url){
if($result = $conn->query("SELECT * FROM $table where $ID = '$url' "));
$atraction = $result->fetch_array(); ?>
<option value="<?php echo $atraction['lat']. "," . $atraction['lon']; ?>"
> <?php echo "<b>".$atrction['City']. ", " . $atraction['Name'];?> </option>
<?php
}
}
?>
</select></td></tr>
<br>
</table>
</form>
And getting ID-s from url code:
if(!empty($_GET[$ID])){
$urls = $_GET[$ID];
foreach($urls as $url){
// echo $url;
}
}
... and after submit, it Post to URL some variables like this:
http://127.0.0.1/responsiveweb/travel.php?actual_position=Paris&final_position=Praha&ID[]=23&ID[]=15&ID[]=55
... very important for me are ID-s values ... but when I change for example actual position and then submit I lost my ID-s and I get something like this: http://127.0.0.1/responsiveweb/travel.php?actual_position=Berlin&final_position=Praha
Can you help me how to get after clicking on submit button full url link? Thanks
I had some trouble understanding your question OP, but I think I understood somehow what you ment, so I decided to try giving you a answer.
I have re-written your code, and tried to make somehow better code-structure. I have also used form method POST in my example, so you can see how you can change the get data on the redirection url.
See my code example here: http://pastebin.com/wQ7QCBmt
I also decided to use the form method POST instead of GET, so you can easily do back-end tasks, and extend your link if neccessary. You could also add more data to the link even when using GET. You could add an hidden input inside your form, example:
<input type="hidden" name="more_data" value="a_value" />

send php post variable to url using javascript when button is clicked

I have a php page which gets $page and $user using post method, I also have a button that i want, to open a URL in the same window using $page and $user variables when clicked, to use them with $_GET[] function.
i want my URL be like:
http://www.test.com/test.php?page=$page&user=$user
my code is like this:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
<html>
<head>
function openurl() {
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
}
</head>
<body>
<button onclick="openurl()" type="button">open url</button>
</body>
</html>
There is no need for scripting at all
If you want GET:
<?php
$page=$GET_['page']; // should be sanitized and you can use REQUEST for either
$user=$GET_['user'];
$parm = "page=".$page."&user=".$user;
?>
Open URL
If you need to post:
<form action="test.php" method="post">
<input type="hidden" name="page" value="<?php echo $page; ?>"/>
<input type="hidden" name="user" value="<?php echo $user; ?>"/>
<input type="submit" value="Open URL" />
</form>
Change these lines:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
....
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
to this:
<?php
$page=$_POST['page']; //incorrect $_POST declaration
$user=$_POST['user']; //incorrect $_POST declaration
?> //php tag incorrectly closed
....
var user=<?php echo $user;?>; //echoing a variable not string (no need for quotes)
var page=<?php echo $page;?>; // echoing a variable not string (no need for quotes)
open('www.test.com/test.php?page='+page+'&user='+user,'_self'); // link was broken, forget to put '+' after page variable in link.
You can create a form and via Javascript just run YOURFORMNAME.submit();
Use href in javaScript to move to another location:
location.href="www.test.com/test.php?page='+page'&user='+user"

Categories

Resources