I'm currently coding a sports website with an editor of teams and players. My concerns are about the editor of teams.
I have a HTML input with a datalist which is built with an array.
I want to let the user choose between an exiting team (ID + Name), or write a new one. I chose to use the datalist, but the datalist doesn't work as a select object. For the datalist, for each option I put the ID in the attribute "data-value" and the name in the attribute value.
My problem is to get the data-value when I chose an option. When I choose an option it doesn't update the data-value of my input text.
<input name="Equipe" list="EquipeTest" type="text" id="Equipe" value="<?php echo $NomEquipe ?>" data-value=<?php echo $IDEquipeJoueur?>" >
<datalist id="EquipeTest">
<?php
for($k1 = 0; $k1<=$Compteur; ++$k1){
echo "<option data-value='".$ListeEquipe[$k1]['ID']."' value='".$ListeEquipe[$k1]['Equipe']."' >".$ListeEquipe[$k1]['ID']."</option>";
}
?>
My goal is to get the ID in the $_POST instead of the value.
I try with javascript, but there is no possibility to add an event on an option.
I can also get the value of the field and find the ID in the array... but it's not a good solution.
Thanks in advance,
J-E
Related
I'm stuck here.
I have a 'working' function below (for each PHP array row, I"m creating a div with a form. The form has an empty input, a '+' button, and a submit button).
Using the first form/div, if I click the '+' button it adds an input field every time up to 10, which is exactly what I want.
However, when I do this on the 2nd, 3rd, or 4th form it adds inputs, but all of them to the first form. So if I click the '+' button on form 2, it adds an input to form 1. I know this has to do with having a non-unique button id and carrying that through my form inputs but I'm totally stuck on what to do here.
I need each form/div to have it's own independent fields, '+' button and submit button. Reason being, I'm going to add an AJAX call to the submit button that will submit any added input values for that given form (using the ticker ID given here `
`<?php echo $ticker['ticker'] ?>``) .
How can I fix this functionality to work for as many divs/forms as I have at any given time?
<div class="row">
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
</div>
<script type="text/javascript">
var maxItems = 1;
function moreItems(button) {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$($(button).sibling('br')[0]).insertBefore($(button));
$($(button).sibling('label')[0]).insertBefore($(button));
$($(button).sibling('input:text')[0]).insertBefore($(button));
maxItems++;
}
}
</script>
Tom, the id attribute for an HTML element needs to be unique, always make sure to use unique id's, if you want to do something for elements that are similar in most ways, use class, on a side note to solve your problem:
Also change your Html to this (pass the button into the function)
Also I changed your id to a class as moreItems_add and removed the id entirely:
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
//Accepts the button object
function moreItems(button) {
//Instead of using a global iterator, grab the number of siblings of input type text
const currentInputs = $(button).siblings('input:text').length;
//Now use this variable to check if we hit the max of ten
if(currentInputs < 10){}
replace these lines:
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
with these lines:
//$(button) refers to the button which was clicked
//.siblings() will check the node structure for element(s) with the given selector on the same level as the button
//pass the jquery object of the button which was clicked into insertBefore()
//Pass the newly created object into the line of code before calling .siblings
//These 2 are inserting the new label and input
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
//Insert a line break so that the next label and input are on new line
$('<br/>').insertBefore($(button));
You can't use the same ID to reference different DOM elements, use classes or an ID with a postfix.
If you are calling the JavaScript function to apply to a specific form you should instead call a function with a class name that applies to all of your forms. Instead of using an ID use a class
The ids have to be unique. How about if you "build them" by appending ticket number?.
Something like
id="<? php echo ("Items".$ticket) ?>". Then you can get the element's id in the js, and insertBefore as appropriate.
For the button, it would be something like this:
<button type="button" id="<?php echo "moreItems_add".$ticker ?>" onclick="moreItems(this);">+</button>
Similarly for the form element:
<form id="<?php echo "Items".$ticker ?>" method="post">
This will give each form element and each button element a unique id. --edit->- The idea being you could use that id in the js instead of #moreItems_add here'<br/>').insertBefore("#moreItems_add"); (from the original iteration of the post). That said, I hadn't groked that no object was being sent to the function (ie this here moreItems(this); and button here function moreItems(button). (And on top of all that, jquery is, ahem, not my best thing). The bottom line is: if you need an unique id for the button in the javascript, you will find it now at button.id.
I've searched through the site for this but am coming up empty handed. Here is what I am trying to do:
User selects one of a series of options from a drop list
Two input fields change to reflect this selection, filling the input boxes with data pulled from my database
See the image below for a visual representation of what I mean:
I know that I am going to need JavaScript for this solution, but my JS skills are not so hot (and I think I am having a momentary lapse of brain power today)!
Here's the code that I have so far (don't worry about the outdated PHP):
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_category = $row['item_category'];
$item_title = $row['item_title'];
$item_price = $row['item_price'];
$item_description = $row['item_description'];
echo "<option value=\"".$item_id."\">".$item_title."</option>";
}
?>
</select>
<script>
function update_txt() {
price = document.getElementById('item').selectedIndex.value;
document.getElementById('item_details').value = price;
document.getElementById('item_price').value = price;
}
</script>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
Any help is greatly appreciated! Let me know if you need any clarification. :)
I would json encode the row and store it as a data-attribute on the option, then read the attribute on the selects change event:
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_title = $row['item_title'];
echo "<option value=\"".$item_id."\" data-json='" . json_encode($row) . "'>".$item_title."</option>";
}
?>
</select>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
<script>
$('#item').on('change', function() {
var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
$('#item_details').val(selected.item_description);
$('#item_price').val(selected.item_price);
});
</script>
You can use a combination of PHP, AJAX and JavaScript (or jQuery).
The general idea is as follows:
User selects an option(s)
JavaScript is used to detect the selection and the option(s)
selected
AJAX gets the options selected, formats it and passes it to a PHP "page"
PHP does the SQL queries and passes the values back
AJAX gets those values and populates the current page using standard JavaScript methods
There's a good tutorial here which shows how it fits together: http://www.tizag.com/ajaxTutorial/ajax-mysql-database.php. I would use prepared statements instead of the SQL queries shown in this example though.
I have looked throughout the site and nothing has quite matched what I'm after. I have a form which starts of asking the client to choose the company name from a dropdown. The dropdown is populated from a query as such:
<select name='company_name' id='dropdown'><?php
$result = mysqli_query($con,"SELECT ID, TITLE FROM b_crm_company");
while($row = mysqli_fetch_array($result))
{
$companyName = $row['TITLE'];
$companyID = $row['ID'];
print "<option value='$companyID'>$companyName</option>";
}
?></select>
I then have 3 forms text fields that I need pre-populating based on what is selected from the above and I'm not sure how to do it. So my next three form fields:
<input type="text" value="$contactName" name="contactName">
<input type="text" value="$contactTelephone" name="contactTelephone">
<input type="text" value="$contactEmail" name="contactEmail">
The select statement I'd need to get these three values:
SELECT COMPANY_ID, NAME, TELEPHONE, EMAIL FROM b_crm_contact
WHERE COMPANY_ID = $companyID
The $companyID obviously being pulled from the dropdown at the start. How can I pull the information to the next fields? I'm assuming javascript but not sure how to write it.
Thanks in advance
you need to call ajax on click of your drop down select item
and then need to return string or json from that php file and then parse and put values in appropriate fields
something like this:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
I have a javascript that shows and hides options from a html form. What I am trying to do is be able for the user to add a new category and then write that into the database as an option and add that subject to the option form.
Here is an example of the html code,
<select id="team1" name="team1" style="display:none">
<option value="subcat1">subcat1</option>
<option value="subcat2">subcat2</option>
<option value="subcat3">subcat3</option>
I then want them to be able to add another subcat4 via the website.
the javascript i'm using is an if statement with show and hides from different selects.
The user needs to be able to enter the category name and add it to the relevant select.
Currently im unsure on how to get this to add and save the new subcat4 to the database and to the html.
Any help would be appreciated.
When you first load the page you construct the select element by using the values stored in the database.
Then you can have a form that posts the filled info and stores subcategories into the database. This form may contain the identifier of your select for knowing in which select you are assigning the new option. It could be in a hidden input.
here comes a simple example of that form
<form method='post' action='/your/action/here' >
<input type='hidden' name='main_category' value='team1' />
Subcategory: <input type='text' name='subcategory' value='' />
<input type='submit' name='submit_btn' value='submit' />
</form>
You could also do it without page refresh by using an ajax post (this should be your next step, make it first work the simple way) to store the info and then by appending the option to your select using javascript. Check the jquery append or the appendChild() if you are not using jquery.
With jquery you can do this code to append new child in your select element.
$('#team1').append('<option value="subcat4">subcat4</option>');
First of, I'm new to ajax and Java Script.. I have spend days solving this problem, but I still haven't figured it out. I have read through threads with similar problems but I still can't get it right. So here goes;
Quite simple I want post the checked value from from one of three radio buttons. All I get though is only the value of the first radio button..
I have tried several things, but I stripped down the code so it might be easier see where the problem is :-)
The ajax
<script type"text="" javascript"="">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var svar = $('#svar').attr('value');
var date = $('#date').attr('value');
var email = $('#email').attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "svar="+ svar + "&email=" + email + "&date=" + date,
success: function(){
$('form#submit').hide();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
</script>
The form
<form id="submit" method="post" name="submit" action="">
<fieldset>
<legend>Dagens spørgsmål: <? echo $row['question'];?></legend>
<br>
<input type="radio" name="svar" id="svar" value="1"><? echo $row['opt1'];?>
<br>
<input type="radio" name="svar" id="svar" value="2"><? echo $row['opt2'];?>
<br>
<input type="radio" name="svar" id="svar" value="3"><? echo $row['opt3'];?>
<br>
<input name="email" id="email" type="hidden" value="<? echo $email ?>" />
<input name="date" id="date" type="hidden" value="<? echo $date ?>" />
<br><br>
<button type="submit" class="button positive"> <img src="img/tick.png" alt=""> Svar på dagens spørgsmål </button>
</fieldset>
</form>
Ajax.php
<?php
include ("dbc.php");
// CLIENT INFORMATION
$email = htmlspecialchars(trim($_POST['email']));
$date = htmlspecialchars(trim($_POST['date']));
$svar = htmlspecialchars(trim($_POST['svar']));
//stuff from answers
mysql_query("INSERT INTO answers
(`email`,`day`,`answer`)
VALUES
('$email','$date','$svar')") or die(mysql_error());
?>
Hope one you of you smart guys have a solution.. because this thing i driving me crazy
You have several problems.
First, your HTML is invalid. An ID must be unique, so each radio button must have its own ID. You associate a group of radio buttons by giving them the same NAME. (Having a unique ID then lets you associate a LABEL with each one using the FOR attribute which increases accessibility by making it easier for screen readers and providing bigger click targets).
Second, the value of a radio button is fixed. The question is "Is it successful or not?" and that is determined by seeing if it is checked or not. If you were doing this manually, you would have to loop over each radio button in the group until you found one that was checked (or use a selector that matched only the checked ratio button (:checked)).
Third, you are building your form data by mashing together strings without making sure the data is URL safe (with encodeURIComponent).
The solution is to forget about doing all this manually and just use the jQuery serialize method on the form.
First: you use the same id for several elements. ID-s should be unique, and you should address your elements with class name or other means. So instead of
$('#svar')
yous should use
$('input[name=svar]')
to reference the group of checkboxes.
Second: There is a slight mistake here:
$('#svar').attr('value');
is the value of the first radio button's value attribute, while
$('input[name=svar]:checked').val();
would give you the value of the checked radio button in the group you are selecting with input[name=svar].
Edit: thx #Quentin for pointing out my error.
First thing to know is id should be unique in a html document.
What makes attributes of type ID special is that no two such
attributes can have the same value;
[Quoted from css2 selector docs]
You have assigend same id to three radio buttons.
Now when you use var svar = $('#svar').attr('value');, only the first radio button will get selected. So, irrespective of radio button selected, only the first radio buttons value you will get.
Now, if you want to get the radio button selected you have to use jQuerys :checked selector.