I'm learning to code and i've come across a probably quite easy problem to solve.
I make a request from the database, that returns a number of users. For each user i create a few input fields like name, email etc.
Now what i want to do is use the same php variable (that contains the number of users), to create or repeat a function x times.
This is what i've tried so far.
var j = 0;
while (j <= i) { //i is the variable passed from php, containing the number of useres
j++;
$('#btnEdit'+j).click(function() {
$("#prename"+j).removeAttr('disabled');
$("#surname"+j).removeAttr('disabled');
$("#function"+j).removeAttr('disabled');
$("#prefix"+j).removeAttr('disabled');
$("#phone_number"+j).removeAttr('disabled');
$("#email"+j).removeAttr('disabled');
});
}
The HTML looks something like this:
Input
<label>Prename</label>
<input name="prename" id="prename<?php echo $i; ?>" value="<?php echo $row['db_prename_value']; ?>" maxlength="100" type="text" placeholder="Prename" disabled="disabled" />
Button
<input type="button" id="btnEdit<?php echo $i; ?>"
name="button<?php echo $i; ?>" value="Edit"></input>
To give a short explanation:
If the database returns 2 users, all the above fields are created for 2 users in php. User 1 will have prename1, surname1 etc. while user 2 will have prename2, surname2 and so on.
I won't know how many users get returned by the database so i can't just manually create the above snippet a set amount of times.
To clarify, i've already passed the variable from php to javascript (variable i). The question is how to repeat the javascript function x times, as the snippet i've posted is not working.
As far as my understanding goes, what my code does is iterate through the while loop x amount of times, but stops at this line, since the button is not being clicked.
$('#btnEdit'+j).click(function() {
Maybe i'm just confused about how to do what i'm trying to do.
Let's make an example. If the variable i is 2, i want the loop to create 2 functions, the first function has to be executed when the button with the id btnEdit1 is being clicked, the second function needs to execute when a button with the id btnEdit2 is being clicked etc.
Thanks
Instead of creating multiple function I would recommend you to create single function.
Use custom data-* attribute to persist php variable <?php echo $i; ?> with edit button which can later be fetched using .data(key).
To attach event handler Class Selector (“.class”) to target the elements and using Event Delegation create a single method.
<input type="button" class="btnEdit" data-id="<?php echo $i; ?>" name="button<?php echo $i; ?>" value="Edit"></input>
Script
$(document).on('click', '.btnEdit', function(){
var j = $(this).data('id');
$("#prename"+j).removeAttr('disabled');
$("#surname"+j).removeAttr('disabled');
$("#function"+j).removeAttr('disabled');
$("#prefix"+j).removeAttr('disabled');
$("#phone_number"+j).removeAttr('disabled');
$("#email"+j).removeAttr('disabled');
})
Why you need this?
You can directly write with an onClick event in input as well with the parameter of your id (which means your i value) .
Please take this answer as a key idea
<input type="button" id="btnEdit<?php echo $i; ?>"
name="button<?php echo $i; ?>" onClick="btnEdit(?php echo $i; ?)" value="Edit"></input>
function btnEdit(id)
{
$("#prename"+id).removeAttr('disabled');
$("#surname"+id).removeAttr('disabled');
$("#function"+id).removeAttr('disabled');
$("#prefix"+id).removeAttr('disabled');
$("#phone_number"+id).removeAttr('disabled');
$("#email"+id).removeAttr('disabled');
}
Note: I don't have experience in php . but this is common idea only
Related
I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>
I'm trying to call a javascript function called confirmRemove(title, id) to remove an element from a table. This function should be called when the user clicks on a link that looks like an "X". I attached my code below to show how I went about doing this, but I'm seeming to be having some errors and I'm not sure why. Most of the elements are able to be removed, but for a few when I click the link to call the function, nothing happens. Is there a better way of doing this? Not sure why this would happen.
<td><?php echo '<a onclick="confirmRemove(\'' . $title . '\',\'' . $id . '\')"
href="javascript:void(0)">X</a>';?></td>
You can try this code
<td> <a onclick="confirmRemove('<?php echo $title; ?>','<?php echo $id; ?>')"
href="javascript:void(0)">X</a></td>
You asked if there is a better way of doing this - I would suggest that there is and that it is to use an externally registered event handler bound to the specific HTML elements in question - notably a hyperlink in this example.
If you assign relevant attributes to the hyperlink ( dataset attributes are very useful for this sort of task ) you can process them within your event listener very easily. There is not need for complicated escaping for quotes by adopting this approach and best of all you can separate HTML from Javascript - the event handlers can be in another file
<td>
<a class='removal' href='javascript:void(0)' data-title="<?php echo $title;>" data-id="<?php echo $id;?>">X</a>
</td>
<script>
Array.from( document.querySelectorAll('a.removal') ).forEach( a=>{
a.addEventListener('click',function(e){
confirmRemove( this.dataset.title, this.dataset.id )
});
});
</script>
I am building a website and a webpage contains same elements with element id which is created by a php function so that element id will be unique.
I want to use a jquery append statement to add div element with id created by a php function.How to write jquery append statement?
HTML PART:
<div id="q2s<?php the_ID(); ?>">
<span class="t2"><input type="text" class="t2" id="t2s<?php the_ID(); ?>">
</span> <span id="star2s<?php the_ID(); ?>" class="rating2"></span>
<hr></div>
In html part <?php the_ID();?> is the php function used for getting unique id
JAVASCRIPT PART:
<script>
var getstarid="<?php the_ID();?>";//php function for getting unique id
$(document).ready(function() {
var q2 = $("#q2s"+getstarid);//This is the part i am asking
//about.How to write this statement?
$(q2).append('<div id="q2s<?php the_ID(); ?>"<span class="t2"><input
type="text" class="t2" id="t2s<?php the_ID(); ?>"></span> <span
id="star2s<?php the_ID(); ?>" class="rating2"></span><hr></div>');
});
</script>
in javascript part var getstarid="<?php the_ID();?>";is used for getting unique id.
How to write var q2 = $("#q2"+getstarid);in jquery so that element id can change and jquery append can work according to change in value of php function <?php the_ID();?>?
Thanking you in advance.
With something like this, I usually embed the code/id/whatever in a data attribute in an element on the page.
HTML:
<div id="q2s" data-id = "q2s<?php the_ID ?>">
Then I retrieve it in my javascript using the jquery "data" method:
JAVASCRIPT:
var getstarid=$("#q2s").data("id");
...
var q2 = $("#q2s"+getstarid);//This is the part i am asking
//about.How to write this statement?
$(q2).append('<div id='+getstarid+'><span class="t2"><input
type="text" class="t2" id="t2s"'+getstarid+'></span> <span
id="star2s'+getstarid+'>" class="rating2"></span><hr></div>');
});
This benefits you in two ways, potentially: 1 - It's cleaner. You shouldn't be putting PHP code mixed in with your javascript. 2 - It might save you some database access. I don't know if PHP hits the database every time it hits "". This way, it only calls that function once and then lets jQuery do the heavy lifting.
EDIT: This code isnt for debugging, it is written only as an example and doesnt need completion as the point of it is just seeing the advantages of using a HIDDEN input in a form to retrieve some value. The answers may also be quick and graphic or metaphorical. I dont want a working code, just the advantages of using each methodology. I also fixed an imaginary condition to the while loop and a value for $record_id and placed them so you can understand.
<?php
if (isset($_POST['delete_action'])) {
$deletedRow = $_POST['row_to_be_deleted'];
mysqli_query($connection, "DELETE FROM table_name WHERE record_id = " . $deletedRow);
//Here is where hidden field value is used
}
$someSQL = "SELECT * FROM comments_tbl WHERE postID=$PostRetrievedID";
while ($someFetch = mysqli_fetch_array($con, $someSQL)) {
$record_id = $someFetch['comment_ID'];
$record_content = $someFetch['comment_Content'];
?>
<span>
<?php echo $record_content; ?>
</span>
<form method="post">
<input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>"/>
<input type="submit" name="delete_action" value="Delete comment"/>
</form>
<?php
}
?>
If your question is about why hidden fields even exists, then I have to say that they are used on lots of websites for the exact reason you show in the example.
Lots of times, when you have a form and the user submits it, you need some extra data that the user should not see so that you can manage the data the user submitted. Like in you example, one common use is to atach the ID of the row.
Hello I want change text in textarea on click(change) radio button. I have own database clanok(article) where attributes are nadpis(title) and text. Thanks.
$result = mysqli_query($con,"SELECT * FROM clanok ORDER BY nadpis");
while($row = mysqli_fetch_array($result))
{
?>
<input type="radio" name="nadpis" value="<?php echo $row['nadpis']; ?> ">
<?php
echo $row['nadpis'];
echo "<br>";
}
?>
<textarea name="text" cols="30" rows="5" >
<?php
echo $row['text'];
?>
</textarea>
<br>
<input type="submit" value="Odoslať článok">
First of all, after the page is finished loading, you cannot fetch new stuff from the database and show it on your page (unless you use ajax), so this means that ALL of your rows of text should be loaded and stored somewhere beforehand.
Or, you can use ajax to fetch some new text from the database each time. Both of these solutions would give 2 different types of strain upon your resources.
I'll give you the non-ajax solution, but if you want to hear the ajax one, tell me, and I'll add it here as well. If you want a piece of your website to change upon a click, you can to use javascript to accomplish this. There is also a CSS-only solution based on the current state (selected or not selected) of the radio buttons, but this javascript was easier to write for me. ... so here you go. Solution without ajax, with javascript.
<?php
$radio_button_div_text = ""; //makes a variable to store all the text to be displayed in section 1
$textarea_div_text = ""; //makes a variable to store all the text to be displayed in section 1
$list_of_all_ids_for_js_function = ""; //makes a variable to store something that will later be part of the javascript function
$result = mysqli_query($con,"SELECT * FROM clanok ORDER BY nadpis");
while($row = mysqli_fetch_array($result)) { //while there are rows to get...
//put the different buttons and textareas into two separate variables
$radio_button_div_text += 'input type="radio" name="nadpis" value="'.$row['nadpis'].'" onclick="show_only_one_textarea('.$row['nadpis'].')">';
$radio_button_div_text += $row['nadpis'];
$radio_button_div_text += '<br>';
$textarea_div_text += '<textarea id='.$row['nadpis'].' name="text" cols="30" rows="5" style="display:none;">';
$textarea_div_text += $row['text'];
$textarea_div_text += '</textarea>';
$list_of_all_ids_for_js_function += 'document.getElementById(\''.$row['nadpis'].'\').style.display="none";' }
//now, after you got all the info sorted, show the two areas!
echo $radio_button_div_text;
echo '<br><br>';
echo $textarea_div_text;
?>
<!--now, what you need, is some javascript to make some textareas visible when you click on the corresponding radio button -->
<script>
function show_only_one_textarea(area_id) {
<?php echo $list_of_all_ids_for_js_function; ?>
document.getElementById(area_id).style.display="block"; }
</script>
<!--now, everything will display properly and the javascript will work. here is your submit button -->
<br>
<input type="submit" value="Odoslať článok">
I'm sorry, I didn't test this code out on my own website ... it probably has a nice handful of errors with the ' " quotes. But if you read through it carefully, you will understand the idea of what is trying to be done there. Do you know anything much about javascript? Feel free to ask me more, if you need clarification!
Good luck.