Class name not working when called in Javascript? - javascript

I have a webpage in which there is a form with diffrent elements, in that there is also a Textfield which searches the names from the database and display it in a dropdown fashion.
Below that there is one more field that which is a button , through which i can add new TextField , same as above.
In that newly added TextField, I want the same AutoComplete feature as done above.
I have given the class names all correct but it unable to fetch the Names and show it in a AutoComplete manner.
NewUser.php
<?php
$db = pg_connect("host=hostname port=5432 dbname=dbname user=vnaem password=root");
pg_select($db, 'post_log', $_POST);
$query=pg_query("SELECT id,name FROM users_users");
$json=array();
while ($student = pg_fetch_array($query)) {
$json[$student["id"]] = $student["name"];
}
$textval = json_encode($json);
$foo = "var partnames=" . $textval;
file_put_contents('autocomplete-Files/NewEntryValues.js', $foo);
?>
. . . . . . . .
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Name: </label>
<div class="col-md-4 col-sm-2 col-2">
<input id="partner_names[]" name="partner_names[]" type="text" placeholder="Enter Full Name" class="form-control input-md newentry" style="width: 100%;">
</div>
<script type="text/javascript">
$(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 increme
$(wrapper).prepend('<br><div style="margin-left:50px;"><center><div class="form-group"> <label class=" control-label" for="textinput" style="margin-left:327px;">Name: </label> <div > <input id="partner_names[]" name="partner_names[]" type="text" placeholder="Enter Full Name" class="form-control input-md newentry" style="margin-top: -25px;margin-left: 403px;width: 241%;"> </div> <img src="images/del24.png" style="margin-left: 810px; margin-top: -81px;"></a></div>'); //add input box\
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
. . . . . . . .
<script type="text/javascript" src="NewEntryValues.js"></script>
<script type="text/javascript" src="autocomplete.js"></script>
As you can see above, the class in Input Tag is newentry and in the Javascript also newentry,
I am fetch that newentry class name in a Another which takes care of Database connection and the AutoComplete Logic.
So , how can the get that logic working in this script tag too !
autocomplete.js
$(function() {
'use strict';
var peopleArray = $.map(partnames, function (value, key) {
return { value: value, data: key }; });
// Setup jQuery ajax mock:
$.mockjax({
url: '*',
responseTime: 2000,
response: function(settings) {
var query = settings.data.query,
queryLowerCase = query.toLowerCase(),
re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
suggestions = $.grep(peopleArray, function(search) {
// return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
return re.test(search.value);
}),
response = {
query: query,
suggestions: suggestions
};
this.responseText = JSON.stringify(response);
}
});
// Initialize autocomplete with custom appendTo:
$('.newentry').autocomplete({
lookup: peopleArray
});
});
NewEntryValues.js
var partnames={"19":"ABCD","42":"group","103":"cv","104":"name_to_1","105":"livetest","106":"live2"}
I am using this jQuery-Autocomplete for reference

You are initializing autocomplete on .newentry while your .newentry is not part of the DOM yet
// Initialize autocomplete with custom appendTo:
$('.newentry').autocomplete({
lookup: peopleArray
});
.newentry comes into the picture in $(add_button).click() when you prepend() the .newentry in wrapper.
Initialize your autocomplete after adding .newentry in wrapper.
Updated
In NewUser.php,
$(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 peopleArray = $.map(partnames, function (value, key) {
return { value: value, data: key };
});
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 increme
$(wrapper).prepend('<br><div style="margin-left:50px;"><center><div class="form-group"> <label class=" control-label" for="textinput" style="margin-left:327px;">Name: </label> <div > <input id="partner_names[]" name="partner_names[]" type="text" placeholder="Enter Full Name" class="form-control input-md newentry" style="margin-top: -25px;margin-left: 403px;width: 241%;"> </div> <img src="images/del24.png" style="margin-left: 810px; margin-top: -81px;"></a></div>'); //add input box
//Initialize autocomplete here when it has become the part of the DOM
$('.newentry').autocomplete({
lookup: peopleArray
});
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});

You need to initialize text input after it has been appended to DOM.When you use .newentry as selector it gets elements that are part of DOM currently, but not the elements that will be appended later.

Try something like this. Carefully go through the code. It is a part of my previous code and it works wonderfully. I have got the values in text box but as you can see in my php code i have commented the code to get the values in a drop-down.
Your php file (autocomplete.php)
<?php
$searchTerm = $_GET['term'];
$query = mysql_query("select name from test where name LIKE '%".$searchTerm."%' ORDER BY name ASC"); // Run your query
/*echo '<select name="taskname">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';*/
while ($row = mysql_fetch_array($query)) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
?>
Your HTML File:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function()
{
$( "#skills" ).autocomplete({
source: 'autocomplete.php'
});
});
</script>
<td><input id="skills" name="taskname"></td></tr>
<label for="skills">Task Name: </label>
<input id="skills">

Related

how do I populate html form fields from a dynamic form dropdown

I am trying to figure out a way to fill html form fields based on the selection of a dynamic form dropdown menu.
I have been looking around and trying to tweek what I have found. So far I am up to filling one of my form fields. But have no gone off piste trying to fill all three, leaving the radio empty when I want it to pick up the 0 value on all my dummy entries and select enable (0)
<option value="<?= $row['ENABLED2'] . " - " . $row['ID2'] . " - " . $row['SOLDTO2'] ?>"> ..</option>
<?php
}
?>
</select>
...
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
});
});
</script>
...
<FORM id='addClient' action='process/process-addclient.php' method='post'>
<input type='text' id='ID2' name='ID2' maxlength='4' placeholder='Four Digit Sage Code' style='display:inline'>
<textarea id='SOLDTO2' name='SOLDTO2' placeholder='Client Name and Address - 6 Lines Max'></textarea>
<input type="radio" name='ENABLED2' id='enable' value='0'> <label for='enable'>Enable Client</label>
<input type="radio" name='ENABLED2' id='disable' value='1'> <label for='disable'>Disable Client</label>
In writing this out I have answered some of my own questions but I cant figure out how to get the last column (radio) to populate.
I am new to JS/JQ
The way to populate the radio field is by using the following code:
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
//Check radio field based on value of GetValueEn
if (GetValueEn == 0) {
$("#enable").prop('checked', true);
}
else {
$("#disable").prop('checked', true);
}
});
});
</script>

Adding dynamic form fields with JavaScript

I have a form that is used to create a JSON array, see my previous question for reference.
In this form a user can add additional details to the fom by clicking a button and filling in said extra details.
These would then be placed into an array in a similar fashion to the below:
<input type="text" name="AdditionalCitizenship[0][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[0][TaxIdentificationNumber]">
<input type="text" name="AdditionalCitizenship[1][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[1][TaxIdentificationNumber]">
This would allow me to grab as many details as the user entered by incrementing the array index.
I was handed this script to add extra form fields.
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap_tel"); //Fields wrapper
var add_button = $(".add_field_button_tel"); //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><div class="row"><div class="form-group col-md-4"><label for="AdditionalTelephoneType">Telephone Type</label><input type="text" class="form-control" name="AdditionalTelephoneType[]" ></div><div class="form-group col-md-4"><label for="AdditionalTelephoneDialingCode">Dialing Code</label><input type="text" class="form-control" name="AdditionalTelephoneDialingCode[]"></div><div class="form-group col-md-4"><label for="AdditionalTelephoneNumber">Telephone Number</label><input type="text" class="form-control" name="AdditionalTelephoneNumber[]" ></div></div>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I am trying to use as is but in this scenario, it is difficult to increment x within the created HTML as it seems to blow up the function.
Could I create the HTML more iteratively like so:
First, create the DIV structure as a wrapper like:
var html = "<div></div>"
Then append an input to this variable called input
var input = document.createElement("input");
input.type = "text";
input.name = "AdditionalTelephoneType[" + x"]";
... and then insert the whole HTML block by using wrapper.append with the variables I have created previously?
You can find the highest x dynamically, see comments:
$("#add").on("click", function() {
// Get the containing form
var form = $(this).closest("form");
// Get all the AdditionalCitizenship fields from it using ^=, see
// https://www.w3.org/TR/css3-selectors/#attribute-substrings
var fields = form.find("input[name^=AdditionalCitizenship]");
// Find the one with the highest [x]
var x = fields.get().reduce((x, element) => {
var thisx = element.name.match(/AdditionalCitizenship\[(\d+)\]/);
if (thisx) {
thisx = +thisx[1]; // The capture group, convert to number
if (x < thisx) {
x = thisx;
}
}
return x;
}, 0);
// Add one
++x;
// Use x
console.log("Next x is " + x);
form.append('<input type="text" name="AdditionalCitizenship[' + x + '][CountryOfResidency]">');
form.append('<input type="text" name="AdditionalCitizenship[' + x + '][TaxIdentificationNumber]">');
});
<form>
<input type="text" name="AdditionalCitizenship[0][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[0][TaxIdentificationNumber]">
<input type="text" name="AdditionalCitizenship[1][CountryOfResidency]">
<input type="text" name="AdditionalCitizenship[1][TaxIdentificationNumber]">
<input type="button" id="add" value="Add">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

datepicker used in textbox inside script

when I use date picker in text box outside script it works fine, iwhich looks like this.
<input type="text" id="entry_date" name="entry_date[]" class="form-control datepicker" data-date-format="<?= config_item('date_picker_format'); ?>" value=""/>
But when I use same date picker function inside script it's not working and I don't know whether it will work like this what the way I gave.Here is my code
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#datepicker1").datepicker();
});
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div class="form-group"><input class="form-control date_pick datepicker col-lg-2" id="datepicker1" placeholder="yyyy-mm-dd" type="text" name="entry_date[]" value=""/></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
});
</script>
Can You please explain to me howI should call this date picker?
Thank You
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<button class="add_button">Add</button>
<div class="field_wrapper"></div>
<script type="text/javascript">
$(document).ready(function () {
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = ''; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
fieldHTML = '<div class="form-group"><input class="form-control date_pick datepicker col-lg-2" id="datepicker' + x + '" placeholder="yyyy-mm-dd" type="text" name="entry_date[]" value=""/></div>';
$(wrapper).append(fieldHTML); // Add field html
$("#datepicker" + x).datepicker();
}
});
});
</script>
Check html appended properly, or put html code separate to jquery, maybe using jquery code appended lately when datepicker function work.
Regards,

add and remove input field function

I have a problem with the deleting function, is my code wrong or something? The add function is working fine though..........
plus how to insert the data from the added input field into the
database?
<script>
$(document).ready(function()
{
var max_fields = 25;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1; //initial text box count
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label for="no_telefon">No.Telefon: </label><input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: </label><input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">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>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<label for="no_telefon">No.Telefon:</label> <input type="text" id="no_telefon" name="no_telefon" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')" required/>
<label for="lokasi">Lokasi:</label> <input type="text" id="lokasi" name="lokasi" class="required input_field" required/>
</div>
</fieldset>
the sql.......
<?php
require("dbase.php");
if ($_POST) {
$id_akaun = isset($_POST['id_akaun']) ? $_POST['id_akaun'] : '';
$daerah = isset($_POST['daerah']) ? $_POST['daerah'] : '';
$kategori_akaun = isset($_POST['kategori_akaun']) ? $_POST['kategori_akaun'] : '';
$bahagian = isset($_POST['bahagian']) ? $_POST['bahagian'] : '';
$jenis = isset($_POST['jenis']) ? $_POST['jenis'] : '';
$no_telefon = isset($_POST['no_telefon']) ? $_POST['no_telefon'] : '';
$lokasi = isset($_POST['lokasi']) ? $_POST['lokasi'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
$sql = mysql_query("INSERT INTO maklumat_akaun VALUES ('', '$id_akaun' , '$daerah' , '$kategori_akaun' , '$bahagian' )");
$sql = mysql_query("INSERT INTO detail_akaun VALUES ('', '$jenis' , '$no_telefon' , '$lokasi', '".mysql_insert_id()."' )");
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='lamanutama.php'</script>";
}
?>
The parent of the clicked button is not div so this expession $(this).parent('div').remove(); does nothing. Use closest method instead:
$('fieldset').on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).closest('div').remove();
x--;
});
Demo: http://jsfiddle.net/11jdyrdf/
PFB code , hope it helps . The problem i feel was you were binding click event for remove on document.ready so at that point of time that anchor for remove was not created as it's being created on add , so click event was not getting binded. Have binded it on add handler.
$(document).ready(function()
{ var max_fields = 25; var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button");
var x = 1; //initial text box count
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label for="no_telefon">No.Telefon: <input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: <input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box
}
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent().parent().remove(); x--;
});
});
});
You haven't put closing tag of label
Make your code perfect you have written wrong code..
Replace your appending code with this one
and then parent() will work
$(wrapper).append('<div><label for="no_telefon">No.Telefon: </label><input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: </label><input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box

JQuery: How to save dynamically added form inputs after validation fails in cakePHP

I have a problem with my registration form. So, I have some fields that are generetad when user click on link, and those fields are lost after I press form Submit button if validation fails. If validation pass, everything is correct and data is saved into database.
So these are that fields, and also script to add new field:
<script>
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var FacebookInputsWrapper = $("#FacebookInputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#FacebookAddMoreFileBox"); //Add button ID
var x = FacebookInputsWrapper.length; //initlal text box count
var FieldCount=0; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(FacebookInputsWrapper).append('<div style="margin-top:10px;"><input id="SocialMediaLink' + FieldCount + 'Link" type="hidden" name="data[SocialMediaLink][' + FieldCount + '][type]" value="fb" /><input id="SocialMediaLink' + FieldCount + 'Link" type="text" name="data[SocialMediaLink][' + FieldCount + '][link]" class="input-xlarge" placeholder="Facebook link" /><a style="background:0;color:black;" href="#" class="facebookremoveclass">×</a></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".facebookremoveclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
</script>
HTML
<li><label>Facebook</label>
<div >
<div style="float:right; margin-top:10px;" id="FacebookInputsWrapper"><?php echo $this->Form->input('SocialMediaLink.0.type',array('type'=>'hidden','value'=>'fb')); ?><?php echo $this->Form->input('SocialMediaLink.0.link',array('type'=>'text','class'=>'input-xlarge','label'=>false,'div'=>false,'placeholder'=>'Facebook link', 'error' => array(
'attributes' => array('class' => 'inputerror')
))); ?><label style="color:#FF0000;"><?php echo #$valid_social; ?></label>
<a style="margin-left:10px;background : 0;color:black;" href="#" id="FacebookAddMoreFileBox">Add another Facebook account</a></div>
</div>
So my question is: is it possible to save dynamically generated form fields and their values after validation fails and how?
Thank you
If I understand the question properly, you need to show those dynamically created fields in your view after validation has failed. Do it like this, checking $this->request->data for those fields:
<?if (!empty($this->request->data['SocialMediaLink'])):?>
<?foreach($this->request->data['SocialMediaLink'] as $i => $item):?>
<div style="margin-top:10px;">
<?=$this->Form->hidden('SocialMediaLink.' . $i . '.type', array('value' => 'fb'))?>
<?=$this->Form->input('SocialMediaLink.' . $i . '.link')?>
</div>
<?endforeach;?>
<?endif;?>
Alternatively, you could trigger the click event on AddButton the right amount of times on page load, based on the number of elements in $this->request->data['SocialMediaLink']

Categories

Resources