Getting input value that has its own iterated button upon click - javascript

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;">

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

Delete a div on a button click (changing id)

I'm generating div with class and id changing. They are all the same and each one has a delete button.
I want to delete the div in which the clicked button is. Each button as the id "delete_index" in a "past_experience_index" div. In fact, when i click on delete_2, i want past_experience_2 to be deleted.
I tried several things but it does not work...
Here is the PHP :
<div class="experiences_container">
<?php
if (!empty($experiences)) {
$index = 0;
foreach ($experiences as $key) {
?>
<div id="past_experience_<?=$index?>" class="past_experience">
<div class="experience_header">
<div>
<label for="team">Nom de l'équipe</label>
<input class="team" name="team_<?= $index ?>" value="<?= $key['team-name'];?>"/>
</div>
<div>
<label for="role">Rôle dans l'équipe</label>
<input class="role" name="role_<?= $index ?>" value="<?= $key['team-role'];?>"/>
</div>
</div>
<div class="experience_textarea">
<label for="description">Description du rôle</label>
<textarea class="description" name="description_<?= $index ?>"><?= $key['team-description']; ?></textarea>
<label for="palmares">Palmarés avec l'équipe</label>
<textarea class="palmares" name="palmares_<?= $index ?>"><?= $key['team-palmares']; ?></textarea>
</div>
<p id="delete_<?=$index?>" class="delete_button">supprimer</p>
</div>
<?php
$index++;
}
} else {
?>
<div><p>Vous n'avez encore rentré aucune expérience</p></div>
<?php
}?>
</div>
So as a JavaScript beginner, i tried a for() with the php index value limit but it doesn't work. The $("div").remove(past_experience_index) works, but i can't have the actual index.
Thanks a lot
Define an onclick function on button click pass $index as a function argument.
<p id="delete_<?=$index?>" class="delete_button" onclick="del_div_fun('<?php echo $index ?>')">supprimer</p>
Now you have to define this function in javascript like.
function del_div_fun(index_val){
var div_id = 'past_experience_'+index_val;
$('#'+div_id).remove();
}//end of function del_div_fun
Please use jquery library
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If your using jquery you don't really need to worry about ids. You can use jQuery to find the parent and remove it that way.
Something like this:
$(".delete-btn").click(function(){
$(this).parent().remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="padding:10%;background-color:lightgrey;text-align:center;">
<p style="cursor:pointer;" class="delete-btn">Delete</p>
</div>
Probably you don't need to duplicate indexes everywhere.
And you can avoid adding jquery into your page.
<script>
function deletePastExperience() {
var experiencesContainer = document.querySelector('.experiences_container');
var elementToRemove = document.getElementById(event.target.parentElement.id);
experiencesContainer.removeChild(elementToRemove);
}
</script>
<p onclick="deletePastExperience()" class="delete_button">supprimer</p>

Assigning a selected value from a dropdown list to a php variable onchange, without pressing submit button in a html form?

I have a html form and a dropdown list like this:
<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div>
<span>Select Event</span>
<select id = "events" onchange="run()" class = "pass" style="width: 209px">
<?php while($row = oci_fetch_array($curs)):?>
<option value="<?php echo $row[0];?>"><?php echo $row[1];?></option>
<? endwhile; ?>
<input type="submit" name="action" value="New Event">
</select>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
</div>
</form>
I can successfully show the values that I take from the database table. And after that I want to use the selected value for another query which needs this selected value simultaneously without pressing submit button.And my run function is like:
<script>
function run() {
document.getElementById("srt").value = document.getElementById("events").value;
}
How can I assign this selected value to a php variable simultaneously?
`
It is not possible.
PHP script will never execute on onchange event.
Don't confuse it with JavaScript.
PHP scripts will only run on events like GET, POST, etc.

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" />

form with 2 buttons need to call different functions based on value

I have a page which has lot of post data in the url.
For example,
www.test.com/test.php?userid='tester'&name=test&so on
The above page has a form that has something like this:
<?
$set=get_value_set;
if($set ==1) {
$set_value="SET";
} else {
$set_value="UNSET";
}
?>
<form name="test">
<input type="text" readonly="READONLY" value="<? echo $user_id; ?>">
<input type="submit" value="Email" name="submit_user">
<input type="submit" value="<? echo $set_value; ?>" name="submit_user">
<?
function setuser()
{
//sets the value
}
function email_user()
{
//sets the value
}
?>
there are two buttons above, when I click on email, i want the value of email button to be passed to the email_user function and do some proceesing there. Similar thing when I click on the set button.
NOTE:But in both cases above, I want the form to remain in the same page with the same post data in the url, but I also want the page to be refreshed so that the set button can have a value of Set or Unset depending on the database update.
Is this possible?
I would start to remove the submit action of each button and change them to
<input type="button" class="btn-Email" value="Email" name="submit_user" />
<input type="button" class="btn-Other" value="<? echo $set_value; ?>" name="submit_user" />
and then, using jQuery, you can easily process each click and submit the form
$(function() {
$(".btn-Email").click(function() {
// append anything you want
var but_email_value = $(this).val(), // or $(".btn-Email").val()
btn_other_value = $(".btn-Other").val();
$("form").submit();
});
$(".btn-Other").click(function() {
// append anything you want
var but_other_value = $(this).val(), // or $(".btn-Other").val();
btn_email_value = $(".btn-Email").val();
$("form").submit();
});
});
change your HTML
<form id="test" name="test">
...
<button onclick="email_user();">Email</button>
<button onclick="setuser();"><? echo $set_value; ?></button>
</form>
your functions should submit the form for you:
document.getElementById("test").submit();

Categories

Resources