i have a problem that I want to get the value of pressed button (which generates new input fields everytime it's clicked), and I don't know if I am able to do this..
I have this JS code:
<script type=\"text/javascript\">
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"<select name=idp[]>$options</select>;
</script>
and this php code with html button type
$t_prod = "";
$types = mysqli_query($db, "SELECT id_type, name_type FROM type_prod ORDER BY id_type");
while ($t = mysqli_fetch_assoc($types)) {
$t_prod .= "<button type='button' name='typ' value='".$t['id_type']."' onclick=\"addInput('dynamicInput');\">ADD ".$t['name_type']." </button>";
}
and the PHP code generates me four buttons, and I'd like to know which button was pressed (optimally by the id_type) – so the "special" generated content for each button would be generated. But I can't get the value.. I was thinking of some getting of ($_POST['typ']) and calling the function addInput in it according to the number of button pressed.
I believe it can be solved client side, just use this pointer:
<button ... value="btn1" onclick="addInput(this)">
<button ... value="btn2" onclick="addInput(this)">
then you can access it in your handler, i.e.:
function addInput(obj) {
if(obj.value=="btn1") // generate your innerHTML for the first button clicked
}
the obj is the element which was clicked
Related
`<?php
$i = 0;
$testcount = 0;
while($testcount < 8) {
if($i == 0) {
?>
<input id="info" type="hidden" value="hi">
<?php
} else if ($ == 1) {
?>
<input id="info" type="hidden" value="test">
<?php
}
?>
<button onclick="test()" class="btnT">Hello</button>
<?php
$testcount++;
}
?>
<style>
.test1 {
background-color: cyan;
color: black;
}
</style>
<script type="text/javascript">
function test () {
$(".btnT").addClass("test1");
}
</script>`
Ignore the if statement, I have not yet implemented it to the js
I am displaying buttons using php while loop without any text nor class. A class is determined using an if statement using php where they will hold a hidden input value which will then be pushed to javascript which will then add a class depending on the value of the hidden input, I am then trying to remove and add another class to only one individual button displayed in the while loop. I either get the first button to get the change, or it changes all of the buttons, and not the individual button that I clicked. Please help, Thank you!
My biggest question is how to make each button inside the while loop to have the event occur individually, instead of all of them. I know that it is because I have the code to add a class to the button class, I tried replacing the button class with an id, but that way, only the first button will get the new class added and not the rest of the buttons. Hopefully there is a solution for each button to act separately
When you create your while loop you can append the $testcount to the end of an ID for the button, this way each button will have its own unique ID, but still have a 'template' name that you can use in javascript.
<?php
$i = 0;
$testcount = 0;
while($testcount < 8) {
echo '<button id="btn'.$testcount.'" onclick="test('.$testcount.')" class="btnT">Hello</button>';
$testcount++;
}
?>
Afterwards you should get 7 buttons with ID's btn1, btn2, btn3, btn4... etc
Then in Javascript you can run a function based off each button like this:
function test(x) {
var myButton = document.getElementById('btn' + x);
myButton.classList.add("test1");
// Any more JS logic you have
}
When you click, for example, button #2, the ID of that button should be 'btn2'. The onclick of the button will send the number '2' as an argument to the JS function. The variable myButton will get the element by the ID of the btn + the number you gave it to create a string like 'btn2', then based off that you now know which button was pressed, and you are able to run actions based off that. Using your example you added the class 'test1' to that button.
So basically I'm creating a program that allows the user to create and manage a ‘to-do list’. This will allow the user to add new items, remove selected items, highlight/un-highlight selected items, and sort the items, etc. I'm currently working on the add button, but I'm extremely confused with different functions in HTML and code that will allow me to manipulate the DOM.
When the user clicks the add button and the item name is valid, a new item should be added to the page’s to-do list (which esentially creates a new checkbox for every item the user adds). The checkbox is basically so the item can be selected/deselected, as well as the text that was in the item name textbox when the add button was clicked.
I guess I have two problems right now. I'm trying to verify that the item name is at least 1 character long. I wrote code in my "addHandler.js" file but when I write nothing in the textbox and click on the add button on my HTML browser, no error message pops up. I don't know why it's ignoring my function. Another thing I'm struggling with is the part that creates a new checkbox for every valid item that is added. I know how to create a checkbox on my HTML page, but I don't understand how to get my program to create a new one per item that the user inputs.
Any help or push in the right direction would be appreciated. I'm also new to HTML and javascript, so explaining stuff in simple terms would also make me really grateful.
todo.html code:
<html>
<head>
<title>Checklist</title>
</head>
<body>
<div><h1>My to-do list</h1></div><br />
<div id ="myCheckList">Enter an item:</div>
<div>Type something: <input type="text" id="textbox"></input></div>
<button type="button" id="addBut">Add item</button>
<button type="button" id="removeBut">Remove items</button>
<button type="button" id="toggleBut">Toggle highlight</button>
<button type="button" id="sortBut">Sort items</button>
<script src="addHandler.js"></script>
</body>
</html>
addHandler.js code:
function init(){
let button = document.getElementById("addBut");
button.onclick = buttonClicked;
let tb = document.getElementById("textbox");
tb.onblur = validate;
}
function add(){
let someEle = document.getElementById("myCheckList");
someEle.innerHTML = 'You added an item';
}
function validate(){
if(document.getElementById("textbox").value.length == 0){
alert("You need to enter something");
}
}
You should have a wrapper that contains your checkbox items that you can append new elements to.
<div id="checklist_items"></div>
Then you can use the following function to create a new div that contains a checkbox and the entered text, and then append it to your checklist:
function addItem() {
var input = document.getElementById("textbox");
var wrapper = document.getElementById("checklist_items");
if(input.value.trim() != "") {
var new_element = document.createElement("DIV");
new_element.innerHTML = '<input type="checkbox"> '+input.value;
wrapper.appendChild(new_element);
}
else {
alert("You must enter at least 1 character.");
}
}
I would also use the following to add the function to your button:
document.getElementById("addBut").addEventListener("click", addItem);
I want mutliple radio buttons (number unknown, because they get created dynamcially) to have the same onClick or onChange event, whichever fits the best. I found examples for jQuery but not pure Javascript. Should i just loop trought all radio buttons on the form?
They get created in php like so:
//DB Connection already established
$sql = "SELECT * FROM users";
$results = $dbConnection->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch-assoc()){
echo "<li><input type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
}
}
else
{
echo "<p>No users found</p>";
}
How can i do that loop? Or is there any more common way of doing that?
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Or Should i just add onclick=myfunction(this) into the php file?
I want multiple radio buttons (number unknown, because they get created dynamically) to have the same onClick or onChange event.
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Let's assume that your PHP has rendered the list items and you have a common function called myFunction() which you want to use to log it's parameter to your console:
function myFunction(val){
console.log("The value is " + val);
};
Now if I understand you correctly, you want to run the above function whenever one of the rendered radio buttons are clicked and to pass the value of the value attribute of the radio button that was clicked as a parameter for the above function.
Firstly, you need to assigned all the rendered radio button in your list to a variable:
var x = document.querySelectorAll("li input");
Secondly, since x is a collection of objects (here, all the radio buttons rendered), you will now have to map through each item on x using forEach and assign a click listener on each radio button which runs the ClickItem()function passing it the item's defaultValue as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.defaultValue;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/56/
However, if by value, you mean the content after the input tag but still inside the respective li tag, then you just need to make slight changes to the above code like this:
Firstly, to prevent the selector from querying li elements from other parts of the page, you need to wrapped your list items with a div or a ul having a unique ID like this:
<ul id="someList">
//create your list items here
</ul>
Secondly, you need to assigned all the rendered list items to a variable:
var x = document.querySelectorAll("#someList li");
Thirdly, similarly to what we did above, since x is a collection of objects (here, all the list items rendered), you will now have to map through each item on x using forEach and assign a click listener on each list item which runs the ClickItem()function passing it the item's innerText as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.innerText;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/58/
Actually the JQuery make it easier, but you can do the same with pure JS.
the real concept is to capture the event bubbling, try this:
fatherElement => element that is not dynamic
fatherElement.addEventListener("click", function(event){
if(event.target.type == 'radio'){
//do something
}
});
Use this echo line instead yours:
echo "<li><input onchange='yourOnChange(event)' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
I add onchange='yourOnChange(event)' there. And of course remember to add proper js function e.g function yourOnChange(e) { console.log(e); } to your web page.
Or Should i just add onclick=myfunction(this) into the php file?
Yes, you can do that. In that case code will be;
<li><input onclick='myclick('". $row['E-Mail'] ."')' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>"
Now in JS code myclick(email) function can handle anything with email argument.
Pure JS solution:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'radio') {
if(inputs[i].checked)
{
//if radio button is checked
myClick(inputs[i].id, 'checked') //you can get anything apart from id also
}
else
{
//if radio button is not checked
myClick(inputs[i].id, 'unchecked') //you can get anything apart from id also
}
}
}
myClick(id, stat)
{
//YAY!! I have got the id
}
You can do a for of loop if you have querySelectorAll.
Here is an example:
const radios = document.querySelectorAll('input[type=radio]');
for (const element of radios ) {element.addEventListener('click', function(event) {
console.log(event.currentTarget)
})
}
Using pure JS you can select your radio buttons and add event listeners like so:
const radios = document.querySelectorAll('input[type=radio]');
radios.forEach(radio => radio.addEventListener('change', e => {
// radio is your radio button element
});
Same with jQuery:
$('input[type=radio]').change(() => {
//your code goes here
});
I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when getStudentInfo is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.
Where am I going wrong?
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo()"
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
js:
function getStudentInfo() {
var studentLink = $('.student-name-btn').attr('id');
console.log(studentLink);
}
Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.
What most people would do is add events with jQuery and not inline.
//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
console.log(this.id);
});
For yours to work, you would need to pass a reference to the button that was clicked.
onclick="getStudentInfo(this)"
and than change it to use the node passed in
function getStudentInfo(btn) {
var studentLink = $(btn).attr('id');
console.log(studentLink);
}
You can pass the reference to the element being clicked on the onclick event
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo(this)" // << added this which refers to the input
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
And then use that to fetch the id in the js
function getStudentInfo(el) {
var studentLink = $(el).attr('id');
console.log(studentLink);
}
Don't use inline events - there's no need to clutter up the HTML with that. You have a common class on your element, so just make a jQuery handler and use an instance of this
$('.student-name-btn').click(function() {
var id = this.id;
});
Like #epascarello alluded to, you are not selecting the button that was actually clicked. What you should do is have your event handling in your JS, not in the HTML so you can see better how it works and use the this keyword within the closure to reference the clicked button.
$(document).on('click', '.student-name-btn', function(evt) {
// Prevent default if trying to do your own logic
evt.preventDefault();
// Need to use the "this" keyword to reference the clicked element
var studentId = $(this).attr('id');
console.log(studentId);
});
You can do this without inline JavaScript and since you're using jQuery drop the onClick() and the form element:
echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
'.$student['student_permalink'].'
</td>';
You also need to quote the identifier in the array variable, 'student_permalink'.
The jQuery will be this:
$('td').click(function() {
var studentLink = this.id;
console.log(studentLink);
});
I have a problem with complicated JS determination of exact item:
this PHP/SQL code:
$prod = array();
$vys = mysqli_query($db,"SELECT * FROM produkty ORDER BY nazev");
while ($arr = mysqli_fetch_assoc($vys)) {
$prod[$arr['id_typu']][] = "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
$polozky[$arr['id_typu']]= '<select name=idp[]>' . implode(' ', array_values($prod[$arr['id_typu']])) . '</select>';
}
this JS code:
<script type=\"text/javascript\">
function polozky(divName, typ){
var newdiv = document.createElement('div');
newdiv.innerHTML = \" $polozky[1] \"
document.getElementById(divName).appendChild(newdiv);
}
</script>
and this HTML code:
<form method='post'><fieldset>
<button type='button' name='typ' value='1' onclick=\"polozky('dynamicInput', '1');\">Add produkty from cathegory 1</button>
<button type='button' name='typ' value='2' onclick=\"polozky('dynamicInput', '2');\">Add produkty from cathegory 2</button>
<button type='button' name='typ' value='3' onclick=\"polozky('dynamicInput', '3');\">Add produkty from cathegory 3</button>
<div name='dynamicInput'></div>
</fieldset></form>
The problem is, that for each cathegory I want to generate (for every value of button) its own content. Using that $polozky[1-3] I'm querying the database for the right items of that cathegory (for items WHERE id_type=value in bracket). And I can't imagine that for 100 cathegories, I need to manually insert 100 times $polozky[1-100]. There must be some trick to do this. Somehow to store the value or some usage of that parameter (i was thinking of some $num=typ inside of the JS branch, but it's not possible due to the different processing type of JS and PHP).
Do you know, what to do please? ;) Thank you
Try this
<script type=\"text/javascript\">
document.getElementsByTagName("button").onclick = function() {
var newDiv = document.createElement('div');
newDiv.innerHTML = this.innerHTML; //Puts text from button inside new Div
document.getElementById('divId').appendChild(newDiv);
}
</script>
I think this is what you are looking for. When a button is clicked you want to have a function that executes that will take the current text enclosed by the button, add it to a newly created div and append that to the page. You also need to give your last div an ID of "divId".