I'm using jQuery's autocomplete() method on a text field with Object.getOwnPropertyNames(projects) as the source:
$(function() {
$("#project").autocomplete({source: Object.getOwnPropertyNames(projects)});
}
The Object.getOwnPropertyNames(projects) method returns an array of the projects object's property names.
This works just fine. However:
If the user enters a new value in the field (ie, a value that is not already a property of the projects object), then the value gets added as a property when a button is clicked (the page is not reloaded). Button click also resets the field. When I try entering a value in the field now, the suggestions list doesn't show the newly added property (unless I call the autocomplete method again). How do I resolve this?
Psst. If I assign the value of Object.getOwnPropertyNames(projects) to an array, use the array as the source in the autocomplete method and update the array on button click, then the suggestions list shows the newly added value.
The following function handles the button click:
$("#clock").click(function() {
if (!($("#project").val() in projects)) { //If value is not already a property
projects[$("#project").val()] = $("#skill").val(); //skill is another field
}
$('#theForm')[0].reset(); //theForm is the id of the form that contains the fields
}
Try updating the source option of the autocomplete after the localArr is updated:
$("#project").autocomplete("option", "source", localArr);
After the form is submitted, your page refreshes, so the javascript code runs again, and what your javascript code says is to auto-complete the input field with the elements from the given source. You have to make sure your source now includes the new project the user just added.
PHP example:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script type="text/javascript">
var projects;
jQuery(function() {
projects = {project1: 1, project2: 2, project3: 3, project4: 4};
<?php if (isset($_GET['project'])): ?>
projects['<?php echo $_GET['project']?>'] = 'foobar';
<?php endif ?>
jQuery("[name=project]").autocomplete({source: Object.getOwnPropertyNames(projects)});
});
</script>
</head>
<body>
<form action="">
Project: <input type="text" name="project" value="<?php echo isset($_GET['project']) ? $_GET['project'] : ""?>"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
As #mimarcel pointed out, $("#project").autocomplete({source: Object.getOwnPropertyNames(projects)}); only created an array that wouldn't change when I updated the projects object. In order for the suggestions list to reflect changes on the object, I had to use a callback, like so:
$('#project').autocomplete({
source: function(request, response){
response(Object.getOwnPropertyNames(projects));
}
});
Related
I am building a management system in which the admin can select an item from the database table and update the details. To achieve this I have two forms on two pages. The first form is to select the item from table and pass it's ID to the second page where I will use the ID to fetch the details from the table using php. I want to do this with javascript so it will not refresh the page. My question is how to pass this value? I am using the following code, but it is not working.
HTML
<div id="result"></div>
<form action="update_item.php" id="update" method="post" >
<select name="selected" class="form-control" id="myItem" required>
<option>Select item</option>
<?php
<!-- PHP script to select the item -->
?>
</select>
<button id="submit">Select</button>
</form>
JAVASCRIPT
$(document).ready(function() {
$("#submit").click(function() {
var chat = $('#myItem').val();
if(chat=='')
{
alert("Please select an item!");
}
else{
$.ajax({
type: "POST",
url:"update_item.php",
data:{
data:chat,
},
success: function (msg) {
//alert(msg):
$('#result').html(msg);
},
error: function(){
alert('error');
}
});
}
});
});
PHP
Second page
$item_id = $_POST['data'];
$get_item = "select * from items where item_id='$item_id'";
<--PHP script continues-->
You can add a hidden field and send this input back to your server:
<input type="hidden" name="something" value="<?= $_SERVER['id'] ?>" />
And then access it with via:
$_SERVER['id']
If you are not changing the page between forms you should be able to just create a variable on the client side that stores the necessary data. Since the second form is loading into the same environment, any variables you have from the first form will still exist.
From your example, I'm guessing chat is the data you're trying to use in the second form. Right now it is local to the click function (once that function completes the variable disappears). You could either move the declaration of that variable into the global scope (outside of document.ready), or use it as intended inside the success callback. (From your example it is unclear what you are trying to do with this data)
I have the following HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?
I have tried manipulating the code used by Ke Yang where localStorage is used to mirror text in form fields across to other fields. I want to do something similar.
I have one page (a library of downloadables) which contains about 10 lead-generation forms on it. Once filled out and submitted, the form sends the user the downloadable. Simple stuff. But say the user wants to download more than one thing on this page, it doesn't make sense to have them keep filling out the same forms. The forms are exactly the same, same fields and field-names, just different form IDs.
I want to use localStorage so that once a user has filled out one form on the page, they can check a box at the top of any of the other forms and the browser will autofill their data, then they hit submit. Ideally, this data is saved even after they leave the page. Data submission is handled by the form itself, so there's no need for cookies (and localStorage is better).
Here's the (minimalised) code I have so far, which goes under the (function($) { in my scripts.js file:
$( ‘input[name=target]’ ).click(function() {if($(‘input[name=target]’).is(‘:checked’)) {
if (localStorage[“first-name”]) {
$(‘input[name=first-name]’).val(localStorage[“first-name”]);
}
if (localStorage[“last-name”]) {
$(‘input[name=last-name]’).val(localStorage[“last-name”]);
}
if (localStorage[“your-email”]) {
$(‘input[name=your-email]’).val(localStorage[“your-email”]);
}
}
});$(‘.wpcf7-text’).change(function () {
localStorage[$(this).attr(‘name’)] = $(this).val();
});
Above you see the names of the different fields within one form. The HTML looks like this, where the checkbox would need to be ticked to call the stored form data:
<p><input id="target2" name="target2" type="checkbox" value="Downloaded our stuff before?" /> Downloaded our stuff before?</p>
<input type = "text" name ="first-name" class="wpcf7-text">
<input type = "text" name ="last-name" class="wpcf7-text">
<input type = "text" name ="your-email" class="wpcf7-text">
The text previously entered into a form will need to be stored (not cleared) after a user hits submit, allowing them to download more stuff easily after their first download.
Thanks heaps in advance!
It seems to me that there are too many issues in your code
1) $( ‘input[name=target]’ ) . This should be $("input[name='target']") .Check this link for more.
2) Use setItem to set the items
3) You need to use .on to delegate the change
I have to rewrite the html to make this work. Just for demo I used only three input field
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" crossorigin="anonymous"></script>
</head>
<body>
<p><input id="target" name="target" type="checkbox" value="Downloaded our stuff before?" /> Downloaded our stuff before?</p>
<input type = "text" name ="first-name" class="wpcf7-text">
<input type = "text" name ="last-name" class="wpcf7-text">
<input type = "text" name ="your-email" class="wpcf7-text">
<script>
$("#target").change(function(){
if($(this).is(":checked")) {
if (localStorage['first-name']) {
$("input[name='first-name']").val(localStorage['first-name']);
}
if (localStorage['last-name']) {
$("input[name='last-name']").val(localStorage['last-name']);
}
if (localStorage['your-email']) {
$("input[name='your-email']").val(localStorage['your-email']);
}
}
});
$(".wpcf7-text").on("change",function () {
localStorage.setItem($(this).attr("name") , $(this).val());
});
</script>
</body>
</html>
Before applying below solution make sure you have given id to your form and your all form controls will have name and id, name and id of control should be identical.
call bellow function before submmiting form
function beforeSubmmit(){
localStorage["YourFormID"] = JSON.stringify($('#YourFormID').serializeArray());
}
on load of page call bellow function
function onLoad(){
if (loadFromLocal == true){
var fromFileds = JSON.parse(localStorage["YourFormID"])
for(var formfiled in fromFileds)
{
$("#"+formfiled.name).val(formfiled.value);
}
}
}
and one more thing
$('#YourFormID').serializeArray()
this function returns array objects , and each object is having two keys name & value, name is name of form control and value contains value of the control.
Just store this array in local storage and retrieve on load and set if by for loop, no need to do hard coding.
$("form").length
this will give you total forms count
$("form")[0].id
and this will give you id of form, you can put for loop and store all forms in local storage
I have a 'parent' page that is using the following bit of code to pull in a form from a different page on the same domain. There are reasons why I can't just place the form directly on the 'parent'.
<script type="text/javascript">
jQuery("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
function() {}
).hide().fadeIn(1000);
</script>
The form that is pulled in looks like this:
<form action="https://example.com/form/" method="post" id="profile-edit-form" class="standard-form base" target="hiddenFrame">
<label for="field_1">Name</label>
<input id="field_1" name="field_1" type="text" value="Joey-Jojo Jr. Shabadoo">
<input type="submit" name="profile-group-edit-submit" id="profile-group-edit-submit" value="Save Changes " />
<input type="hidden" name="field_ids" id="field_ids" value="1" />
<input type="hidden" id="_wpnonce" name="_wpnonce" value="a62f8d5fec" />
<input type="hidden" name="_wp_http_referer" value="/form/" />
</form>
When 'submit' is clicked, https://example.com/form/ is opened in a hidden iframe and the user name gets properly saved. This all works well.
I would like the user name on the currently loaded 'parent' page to update via jquery, so that the user has some immediate visual feedback that the name change has taken place.
My approach has been to try and take the value out of the 'field_1' input when 'submit' has been clicked, and pass that variable onto a div in the parent page with an id of 'display_name'.
$(document).ready(function(){
function nameUpdate(){
$("#profile-group-edit-submit").click(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
}
nameUpdate();
});
I've also tried adding window.parent.
before the the #display_name selector section and it didn't change anything.
I've used this approach on another button/div combo on the same page and it works, the difference is that that particular button is in an iframe, not loaded by jquery. So I'm guessing my problem is related to that fact.
I've googled around, but have run out of ideas of how to phrase my question, what to look for, etc...
Any help would be greatly appreciated. Thanks!
Edit: For clarity, the div w/ id #display_name won't update.
Use jquery to handle the form submission.
$(document).ready(function(){
$('#profile-edit-form').submit(function(){
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
});
EDIT:
Due to your loading the form dynamically you need to bind the submit function after the load. So...
$(document).ready(function () {
var formLoaded = function () {
$('#profile-edit-form').submit(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
};
$("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
formLoaded
).hide().fadeIn(1000);
});
If I am understanding it correctly, your problem is "display_name" field is not getting updated with the latest value.
If this is the problem then can you try below thing?
Instead of
$("#display_name").text(updateName);
try using-
$("#display_name").val(updateName);
As per the documentation on jQuery site Val() works well with form Elements whereas text won't.
More on Val() method- https://api.jquery.com/val/#val2
Background
Using VanillaJS to obtain an HTML form's action attribute value.
Code
Here is the code and the fiddle:
<html>
<head>
<script type='text/javascript'>
function init() {
alert( document.forms['form-load'].action );
}
</script>
</head>
<body onload="init();">
<form name="form-load" id="form-load" action="http://google.com/q">
<input name="query" id="query" type="text" />
<button id="button-load" type="submit" name="action" value="load">Load</button>
</form>
</body>
</html>
Problem
The dialog shows [object HTMLButtonElement] where http://google.com/q was expected (using Firefox 32).
Question
How can the form's action attribute value be retrieved?
Update
The following question might be relevant:
Retrieve form's "name" attribute in Javascript whereas an input exists with name "name"
It's a bad idea to give form elements names that conflict with standard form property or method names. For example, avoid giving elements the following names: submit, method, action, reset.
If you must, get the attribute value using the .getAttribute() method instead:
function init() {
alert( document.forms['form-load'].getAttribute("action") );
}
I think it's a bad practice to name an attribute name with "name". Why not use id instead?
function init() {
alert( "By ID:" document.getElementById('form-load').getAttribute('action') );
}