I have a form that autocompletes the client name based on the input from the user.
HTML:
<label for="client">Facility Name/Account Number: </label>
<input type="text" oninput="dropdownTip(this.value)" id="client" NAME="client" style="width:100%;">
<label for="iname">Interpreter Name:</label>
<input type="text" style="width:100%; text-transform:capitalize;" id="interpreter" name="iname" value="<?echo $interpreter;?>"/><BR>
Javascript:
jQuery(document).ready(function(){
$('#interpreter').autocomplete({source:'otp_autocomplete.php', minLength:2});
});
jQuery(document).ready(function(){
$('#client').autocomplete({source:'otp_client_autocomplete.php', minLength:2});
});
The same form also populates additional fields based on the value of the client field using the following php generated javascript:
PHP:
<script type="text/javascript">
function dropdownTip(value){
var preamble = 'No Special Instructions';
<?//Load options from DB.
while($row = mysqli_fetch_array($statuses)){
echo "if(value == '" . $row['client_id'] . " - " . str_replace("'","\'",$row['client_name']) . "') {
preamble = '" . $row['Special_Instruction'] . "';
} ";
}
?>
console.log(value);
document.getElementById("result").innerHTML = preamble;
}
</script>
Everything is working great, except that I would like the function "dropdownTip" to trigger as soon as the autofill option is selected. Currently it only activates once another field is clicked on, and does not activate at all in Internet Explorer.
I have been trying different HTML DOM events listed here:
https://en.wikipedia.org/wiki/DOM_events
But I can't seem to find the right one. Is there one that will provide the functionality I am looking for, and work with IE?
Related
I have a dropdown that uses JQuery/Javascript within my php/html program.
This works fine if I hard code the name of the program that runs the SQL to load data into the dropdown list.
I would like this code to be re-usable rather than duplicate it for each dropdown list (I want 2 in the current instance) so I would like to know how to pass different program names as each dropdown list accesses different files. Example: ClubID dropdown requires data from clubs using clubsSearch.php but MemberTypeID requires data from memtyp using memtypSearch.php.
Here is the Javascript including my latest effort to pass the program name as a variable:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("click input", function()
{
/* Get input value on change */
var srchName = <?php echo $SearchName?>;
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get(srchName, {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
If I use
$.get("clubsSearch.php", {term: inputVal}).done(function(data){
it works fine.
The relevant section of the form is:
<div class="col-6 col-md-4">
<div class="form-group <?php echo (!empty($ClubIDer)) ? 'has-error' : ''; ?>">
<label>Club ID:</label>
<div class="search-box">
<input type="hidden" name="clubID" value="<?php $SearchName = "\"clubsSearch.php\"";?
>" >
<input type="text" name="ClubID" autocomplete="off" class="form-control"
value="<?php echo $ClubID; ?>" >
<?php echo $SearchName?>
<div class="result">
</div>
<span class="help-block"><?php echo $ClubIDer;?></span>
</div>
</div>
</div>
The **$SearchName** displays as "clubsSearch.php" but in Chrome's developer tools I can see the javascript has not recognised the variable var srchName = ; x and no dropdown list appears.
Can anyone tell me how to present the search name to the javascript as I am completely unfamiliar with it. Any assistance would be appreciated.
Pass the program name in the data- attr like
<select name="WHATEVER" id="WHATEVER" data-program="YOUR_PROGRAM_NAME">
in JS get it like
var srchName = $(this).attr("data-program");
Resolved: In the html
<input id="ClubID" data-pgm="\"clubsSearch.php\"">
and in the Javascript
var srchName =input.dataset.pgm
I'm trying to prep forms with multiple (dynamic) inputs to insert correctly via ajax.
Currently, using my php loop, I have 4 div/forms. Each form has a starting input, and upon clicking the moreItems_add button, it dynamically adds another input, up to 10 per form/div.
This works fine. But I added a variable and console.log to log the value of my hidden input though, which should be getting an ID (<?php echo $ticker['ticker'] ?>) for each form, but it's currently only logging '1'. So when I clicked the button in the first form it looked right, but when I click the others, it's still 1. I think this is because I don't have a unique ID on the hidden input?
How can I change the way I'm keeping track of the hidden input so that I can make an ajax call that will only make an insert on the inputs of the given form WITH the correct ticker ID?
<?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">+</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;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
To generate a unique id attribute you should append your ticker value from php to... the id attribute. Or if not the ticker value, at least something that makes it unique. But you don't really need to.
Since all your elements are wrapped in a form tag and are at the same level, you can find to which ticker corresponds the clicked button by finding the hidden input among its siblings:
var tickerID = $(this).siblings('input[name="tickerID"]').val();
On my site I have a main search (powered by Google, placed throughout the site) and I have now created a second search (on its own page, which searches my DB for images based on user input text) which is a totally separate search to the google one.
What I want to do -
I want both Search forms to share a single text input field, but allow the user to choose which search to use (Google or Images Only) via radiobutton.
So we'd have:
[search input field][go] (o)Use Google (o)Image Search only
I'm no coder but can hack enough to just about get by, it just takes me a day or two to figure out and get working.
What I need and would save me a great deal of time, as I'm stumped on how to proceed with this or if it is even possible! If someone could tell me A) If it's possible, and B) A few pointers if it is. For instance I'm guessing it will probably need a bit of JavaScript to make it possible?
Any pointers would be appreciated, then I can see what I can do.
All the best,
Chris
// My Stand-alone Image Search Page ////////////////////////////////
<form method="post" action="imagesearch?go" id="search-form">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
// code for above form //
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$sql="SELECT ID FROM ImageTable WHERE Name LIKE '%" . $name . "%' Order by Date Desc LIMIT 50";
//-run the query against the mysql query function
$result=mysql_query($sql);
// Create while loop and loop through result set//
$content .= ' <p><div id="wrapper">';
while($row=mysql_fetch_array($result)){
$id=$row['ID'];
$img = new Image($id);
// Format results//
$content .= '<div id="imgrt"><img src="/img/M/'.$img->ID.'.jpg" class="searchimg"><br>'.$img->Name.'';
$content .= '</div>';
}
$content .= '';$content .= '</div>';
}
else{
$content .= ' <p>Please enter a search query</p>';
}
}
}
// End of Stand-alone image search page /////////////////////////
---------------------------------------------------------------------------
// My sites main Google powered Search
<form action="http://www.example.com/gsresults" id="cse-search-box" class="searchmain">
<input type="hidden" name="cx" value="partner-pub-XXXXXXXXXXXXXXX" />
<input type="hidden" name="cof" value="FORID:XX" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="mainsearch">
<input type="submit" name="sa" value="Go" class="mainsearchbutton"/>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang="></script>
OK so here we go. If you plonk this in an empty html file you can see it in action (Tried to make a jsfiddle but didnt work for some reason). What this does is set an "active" id on the selected combo option, and when you click the submit button it grabs the value of the combo option with that id, and goes to the page of that value. so if you click google and then the button you go to google.html, and same goes for image, image.html. If you want some more specifics you can ask, but thats the main logic there.
<script>
function replaceActive(obj) {
var activeElm = document.getElementById("active");
activeElm.id = activeElm.id.replace("active", "");
obj.id = "active";
}
function formFunction(obj) {
obj.action = document.getElementById("active").value + ".html";
}
</script>
<form action="#" onsubmit="return formFunction(this);" method="post">
<input type="text" />
<select>
<option value="google" id="active" onclick="replaceActive(this);">Google</option>
<option value="image" onclick="replaceActive(this);">Images</option>
</select>
<input type="submit" />
</form>
Basically you can change that "formFunction()" function's code and and use "document.getElementById("active").value" to do what ever you wanted to do.
So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo
This has probably been answered before, and I'd like to apologize for reposting, but since I'm not sure where to start fixing it, I'm not sure what to try and look up for a solution. So bear with me please.
I've got a form for a CMS where I've used a tutorial to dynamically add fields where I need them. EX: The form loads with 0 field entries for bullet points, but if they want some, they can click a button that says add bullet, and voila, a entry field appears. It's in an array. Submits to the DB just fine. The delete button is disabled if there's no fields displayed. All that works fine. If you start out with no fields, on a fresh form. The problem falls into the edit version of this form.
Here's my code:
<div id="bullets">
<?php
$sql_bullet_display = 'SELECT * FROM exampleDB.prod_feature_bullets WHERE product_name ="'.$row_product_details['product_name'].'";';
$res_bullet_display = mysql_query($sql_bullet_display) or die(mysql_error().'<br />bad query<br />'. $sql_bullet_display);
$newNum = 1;
while($row_bullet_display = mysql_fetch_assoc($res_bullet_display)){
?>
<div id="bullet<?php echo $newNum; ?>" class="clonedInput2">
<input type="hidden" id="bullet_order<?php echo $newNum; ?>" name="bullet[<?php echo $newNum; ?>][bullet_order]" value="<?php echo $newNum; ?>" />
<input type="text" id="bullet_text<?php echo $newNum; ?>" name="bullet[<?php echo $newNum; ?>][bullet_text]" value='<?php echo $row_bullet_display['bullet_text']; ?>' />
<input type="text" id="bullet_subtext<?php echo $newNum; ?>" name="bullet[<?php echo $newNum; ?>][bullet_subtext]" value='<?php echo $row_bullet_display['sub_text']; ?>' />
</div>
<?php
$newNum++;
}
?>
</div>
<div>
<input type="button" id="btnAdd" value="Add Bullet" />
<input type="button" id="btnDel" value="Remove Bullet" />
</div>
and this is the Javascript that goes with it.
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput2').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
$('<div id="bullet' + newNum + '" class="clonedInput2"><input type="hidden" id="bullet_order' + newNum + '" name="bullet[' + newNum + '][bullet_order]" value="' + newNum + '" /><input type="text" id="bullet_text' + newNum + '" name="bullet[' + newNum + '][bullet_text]" /><input type="text" id="bullet_subtext' + newNum + '" name="bullet[' + newNum + '][bullet_subtext]" /></div>').appendTo('#bullets');
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 15 bullets
if (newNum == 15)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput2').length; // how many "duplicatable" input fields we currently have
$('#bullet' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if no element remains, disable the "remove" button
if (num == 0)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
This has worked really well for me in the past, but like I said, it only works on a fresh form that's starting out at 0 bullet entry fields. My problem lies in creating the edit form. I've already got two bullets in the DB that are displayed when you hit edit. The add button shows enabled. The delete button is always disabled when the form first comes up. Even if there's two entries displayed and everything is filled correctly.
However if I click the add button, so a third entry field will show up, it will enable the delete button. Very frustrating. I'm not sure what to go about editing so it'll say: okay, on the page load, we recognize that the DB already filled out two bullets, so the delete button should be active from the start. Every change I've tried so far just breaks the button.
Thanks in advance for the help!
In your javascript code, you have initiliazed the deletebutton to be disabled. you need to check the number of bullets you have created from db...
Modify your last code from:
$('#btnDel').attr('disabled','disabled');
to
if($('.clonedInput2').length<=0){
$('#btnDel').attr('disabled','disabled');
}
Try this to remove the disabled attribute
$("#btnDel").removeAttr("disabled");