PHP how to use Foreach loop in Javascript - javascript

I want a teacher to select multiple classes when he click a button, the classes are selected from the database and displayed via an tag. I have made a function which makes a new select and displays another list of the classes, however my foreach loop doesn't seem to work...
Here's my JQuery which is inside a 'script' tag in the HTML:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select name="klas" style="width:40%;"><?php foreach ($klas as $klas) {echo "<option value='".$klas->getCode()."'>".$klas->getCode()."</option>"; } ?></select>Verwijder</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
This is the button and the corresponding div's:
<div class="input_fields_wrap">
<button type="button" class="add_field_button">Add More Fields</button>
<div>
<select name="klas">
<?php foreach ($klas as $klas) {
echo "<option value='".$klas->getCode()."'>".$klas->getCode()."</option>"; } ?>
</select>
</div>
</div>
Does someone have any idea how I can achieve the same result from JQuery as from the regular php/html select box?

put your array in arr format in this answer and append to the div wherever you want on page currently i use select_div
<div class="input_fields_wrap">
<button type="button" class="add_field_button">Add More Fields</button>
<div id ="select_div">
</div>
</div>
<script type="text/javascript">
var arr = [
{val : 1, text: 'One'},
{val : 2, text: 'Two'},
{val : 3, text: 'Three'}
];
var sel = $('<select>').appendTo('#select_div');
$(arr).each(function() {
sel.append($("<option>").attr('value',this.val).text(this.text));
});
sel.append("</select>")
</script>

Found it. Your problem is that you use the same value name for both $klas array as well as internal foreach variable. While this is not technically incorrect, notice that after foreach $klas variable will be equal to last element of the array - not the array itself.
Since you were using this loop inside javascript it was tough to spot, and local test with foreach showed that everything is fine.
Anyway please update your code (everywhere were it is used) from:
<?php
foreach ($klas as $klas) {
$klas->getCode()
}
?>
to
<?php
foreach ($klas as $k) {
$k->getCode();
}
?>

Related

How to display array values in input box

I am using appended below script to display multiple input box as per customer needs, as the name is same, so all values are saving in database in an array form. i want to display these values in input boxes once customer save his form. suppose if customer generate three input boxes and set values 1. abc 2. def 3. ghi, how to generate 3 input fields on page load and put these values in it?? i am new to javascript, any help is highly appreciated. Here is my codes:
$value = "abc,def,ghi"
$(document).ready(function() {
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
x++; //text box increment
$(wrapper).append('<div><input type="text" name="new_field_5[]" placeholder="Description"/>Remove</div>'); //add input box
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="new_field_5[]" placeholder="Description" value="<?php echo $value;?>"></div>
</div>
You could create a Ajax request to the php file which returns all of the values for the inputs, and then use a for in loop to assign those values to each input

[Solved]Javascript/Jquery & PHP: getting div ID that's in a loop

Solved: the answer was so simple. I needed to pass the variable into the function but the other coding was helpful. Thanks, all.
$array = array('a', 'b', 'c');
foreach($array as $key=>$info)
{
echo "<form action = 'form' method = 'post'>
<select name = 'choice' onChange = 'changeFunc()'>
<option value = 'first'>first</option>
</select>
<input type = 'submit' value = 'send'></form>
<div name = 'getID' id = '$key'> </div>";
}
function changeFunc()
{
var elements = document.getElementsByClassName('getID');
var key = elements[0].getAttribute('id');
}
So what's happening is that when I try to get the ID of the div that's in the loop, the default answer is the first loop. I'm not quite sure what the logic is to get individual divs that were created in the loop.
Since tagged with jQuery... I suggest you a change event handler for all select that has a name="choice" that will find the id of the div .getID withing its closest form.
$array = array('a', 'b', 'c');
foreach($array as $key=>$info){
echo "<form action='form' method='post'>
<select name='choice'>
<option value='first'>first</option> <!-- You probably need more than one option if you expect a change event ;) -->
</select>
<input type='submit' value='send'>
</form>
<div class='getID' id='$key'></div>"; // A class here instead of a name.
}
$(document).ready(function(){
$("select[name='choice']").on("change", function(){
var key = $(this).closest("form").find(".getID")[0].id
console.log("Select changed... Here is the key:", key)
});
});
// The same in plain JS
window.addEventListener("DOMContentLoaded", function(){
document.querySelectorAll("select[name='choice']").forEach(function(element){
element.addEventListener("change", function(){
var key = this.closest("form").querySelector(".getID").id
console.log("Select changed... Here is the key:", key)
});
});
});
I think,
document.getElementsByClassName('getID') => you get 3 elements
then elements[0].getAttribute('id') => you get first element
That is why you always get the first element id,
you can use this to get individual divs.
function changeFunc()
{
var element = this.closest("form").getElementsByClassName('getID');
var key = element.getAttribute('id');
}

How to display mysql data through javascript in dynamic form field

I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>

jQuery - Limit groups of labels and checkboxes to a max number

I'm trying to limit a max number selectable for checkboxes and their relative labels. Checkboxes work fine but labels are still selectable more than the limit.
My html input is formed like this:
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default <?php echo $labelchk ?>">
<div class="bizcontent">
<input id="youaresure" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
<h5><?php echo $term->name ?></h5>
</div>
</label>
</div>
and my jQuery to limit checkboxes and labels is like:
var $checkboxes = $('input[id="youaresure"]');
var $parent = $checkboxes.parent('label');
var max = 5;
$checkboxes.show();
$checkboxes.change(function () {
$(this).prop('checked', function () {
if ($(this).is(':checked')) {
return ($checkboxes.filter(':checked').length <= max) ? true : false;
}
});
});
$parent.show();
$parent.change(function () {
$(this).prop('class', function () {
if ($(this).is('active')) {
return ($parent.filter('active').length <= max) ? true : false;
}
}
Basically, php inserts an active class to labels parents of inputs:checked and I should prevent both labels and inputs to be selected if more than 5.
For checkboxes is fine but parent labels are still selectable and basically are the visible ones.
EDIT: I've forgotten to indicate that it works with bootstrap and each checkbox is threaten like a button!
There is no change event on <label>. Everything should be done in event handler of the <input>
My suggestion is you disable the other checkboxes when limit is reached.
Following will toggle the active class on label as well as disable/enable unchecked inputs
var max = 5;
var $checkboxes = $(':checkbox').change(function(e) {
var maxChecked = $checkboxes.filter(':checked').length === max;
// disable/enable others based on limit
$checkboxes.not(':checked').prop('disabled', maxChecked);
// toggle label active based on checked state
$(this).closest('label').toggleClass('active', this.checked);
});
DEMO
This doesn’t work because of label has no change handler. Maybe you should better to add your some code into your checkbox’s property check function that removes ‘active’ class of parent labels if necessary.

Dynamically creating a specific number of input form elements

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

Categories