I have multiselect element just like StackOverflow does with their tags. I don't know how to write the jQuery statement that will retrieve the multiple values that were selected.
Here is what I have so far.
HTML
<input id="tagSelect" style="width:400px;" type="text"/>
Here is my Javascript
var tag = $('#tagSelect').val();
Here is the plugin that it uses
http://nicolasbize.github.com/magicsuggest/
There are two ways to retrieve the values with the plugin:
If the combo is included within a classic form like this:
<form method="POST" action="submit.php">
<div id="ms"></div>
</form>
<script type="text/javascript">
var combo = $('#ms').magicSuggest({
data: 'a,b,c,d,e',
name: 'choice'
});
</script>
then the selection will be serialized in the parameter $_POST['choice'].
If you need to retrieve the values through javascript, there is a getValue() method which will return an array of values:
ms.getValue();
This solution does not appear to work.
When trying to execute ms.getValue(); the following error message is logged:
TypeError: ms.getValue is not a function[Learn More]
Related
I am trying to make a dynamic form using HTML and CSS. I am adding parts of my code below. I can not figure out why the code is not working.
JavaScript:
<script>
$(document).ready(function(e) {
var labelfiled = '<div><label>Label</label><input type="text" name="label[]"></div>';
var valuefiled = '<div><label>Value</label><input type="text" name="value[]"></div>';
var labdiv = $(".labdiv");
var valdiv = $(".valdiv");
var addbutton = $(".add_more");
$(addbutton).click(function(){
$(labdiv).append(labelfiled);
$(valdiv).append(valuefield);
});
</script>
HTML:
<form>
<div class="col-md-6 labdiv">
<div><label>Label</label>
<input type="text" name="label[]">
</div>
</div>
<div class="col-md-5 valdiv">
<div>
<label>Value</label>
<input type="text" name="value[]">
</div>
</div>
<button class="add_more">Add values</button>
</form>
If someone can help it would be great.
I also would like to know how I can process the data when I submit this into a javascript variable in the from of a array. Like for example if i have 2 inputs for value in the from, I want to store them in a javascript array and then convert it into a JSON.
Form must be in method="POST" and if you get in into php function :
if(!empty($_POST) && isset($_POST){ /*try something with $_POST*/ }
Try this
$(".add_more").click(function() {
var postData = {
field1: $("#id_field1").val(),
field2: $("#id_field2").val()
};
$.ajax({
dataType: "json",
data:JSON.stringify(postData),
url: URL,
method: 'POST'
});
});
A few things that may improve your learning:
jQuery and you code
All jQuery code should be wrapped in this...
$(document).ready(function() {
// jQuery
});
On the var's you have created, you have already initialised them as jQuery elements. Therefore, when you reference them again, you do not need (for example) $(addbutton) as addbutton will do. See amended code below)
<script>
$(document).ready(function(e) {
var labelfiled = '<div><label>Label</label><input type="text" name="label[]"></div>';
var valuefiled = '<div><label>Value</label><input type="text" name="value[]"></div>';
var labdiv = $(".labdiv");
var valdiv = $(".valdiv");
var addbutton = $(".add_more");
addbutton.click(function(){
labdiv.append(labelfiled);
valdiv.append(valuefield);
});
});
</script>
The console
On checking the console...
Say, for example, if you write the JS code console.log(1 + 1) in your page somewhere as you want to see that sum. Due to you writing client side code, when your web page loads (and depending where you have put the console.log()) if you check the developer tools in your chosen browser i.e. Chrome or IE, there is a console section where you can see the result of what you printed (i.e. using that example, it would be 2). This console in the browser will also print out errors that it detects (i.e. $ is not defined - if you are trying to reference jQuery but the library isn't included), it's a good tool for web developers (hence the name ;)) for debugging client side code.
Adding elements to array
Code for getting input values on submit of a form: (jQuery)
var array = [];
$("form").on("submit", function() {
$("input").each(function() {
array.push($(this).val();
});
});
I would suggest that you go and read a book/tutorial on jQuery code as well as the basic concepts of web development :)
Examples:
jQuery
For reference to basics if you get stuck, the link above is more reliable:
- w3schools
I am working on an Angular application and i have a view who is containing an iframe (The purpose of that iframe is just to display a login form).
Like my attempt to submit the form manually was unsuccessful, i tried to log the formular to check if i am really able to reach it but i am confused about how to do that...
the form inside the iframe have name attribute myForm
<iframe id="myIframe" name="myIframe" src="someUrl.com">
<html>
...
<form name="myForm" class="form" action="myAction()" method="post" onsubmit="myStuffToDO()">
...
...
</form>
...
</html>
</iframe>
So the way that i am trying to log the form in my controller is like that:
var iframeForm = angular.element.find('myForm');
console.log(iframeForm);
the result in hte console is that:
[]
I am really confused about how to do that so any help would be really kind.
.find('myForm') would find <myForm> tags, not tags with an attribute with the "myForm" value. .find('[name="myForm"]') is what you are looking for, but it won't work with the built-in element implementation because .find, as stated in the docs, is "Limited to lookups by tag name".
That means you'll need to also include jQuery in your project. Then Angular will use it instead of its jqLite implementation and complex selectors will work.
You can access using form name withing scope like below:
console.log($scope.formName);
You can access all elements by their names inside formName object.
from the page you can access angular element by angular.element+jquery selector
eg : angular.element("[name='myForm']")
I have a javascript constant and I was wondering if and how I can get that constant in an input form. For example.
<input form="POST" action="INSERT_API_CONSTANT_HERE/myroute" />
I was wondering if it's possible to do something like that. Thanks in advance.
First of all, your HTML tag is wrong. <form> is a different tag from <input>, so to be a form, it should be:
<form id="myForm" method="POST" action="{{api}}/myroute">
<input type="text" value="this is an input" />
</form>
I also provided an <input> tag to you note the difference, now let's go to changing form action dynamically via javascript with JQuery:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
//your "constant"
var MY_CONSTANT = "some_value";
//option A: to set action parameter, replace"{{api}}" text to your "constant" value
var originalAction = $("#myForm").attr("action");
$("#myForm").attr("action" , originalAction.replace("{{api}}", MY_CONSTANT));
//option B: you could leave form action empty in HTML and write everythig here via javascript
$("myForm").attr("action" ,MY_CONSTANT + "/myroute" );
</script>
Both options A and B works, but I don't think replacing a text for another the best solution, I prefer option B in my opinion.
Try this:
$("form").attr("action", $("form").attr("action")
.replace(/INSERT_API_CONSTANT_HERE/g, APIConstant))
I am using jQuery and bootstrap to give drop-down search suggestions.Following is the html code.But when I type something in the search form and then clear the form.Two forms apears as in the picture.Why? I am new to jQuery. Thanks for any help.
<div class="container">
<div class="row">
<div class="span6 offset3">
<form class="form-search">
<input type="text" id="month" name="month" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
<div id="suggestions">
</div>
</form>
</div>
</div>
</div>
<script>
jQuery("#month").keyup(function(){
ajax('search', ['month'], 'suggestions')});
</script>
EDIT:
I am using web2py framwork.This is the search function's code:
def search():
if not request.vars.month: return dict()
month_start = request.vars.month
selected=complete('piracyfinder',month_start) #this line get the search results
return DIV(*[DIV(k['title'],
_onclick="jQuery('#month').val('%s')" % k['title'],
_onmouseover="this.style.backgroundColor='lightblue'",
_onmouseout="this.style.backgroundColor='white'"
) for k in selected])
It appears you are using the same function (i.e., search()) to fill in the suggestions as well as to create the form (though that function doesn't process the form when submitted). According to the logic, when request.vars.month is either empty or does not exist, the function returns an empty dict. This will result in the associated view (i.e., /views/[controller name]/search.html) being executed and returned. Presumably the search.html view contains the HTML code shown above. So, when you clear the input box, the keyup handler is triggered and sends an empty month variable, which results in a new copy of the form being sent back and inserted in the "suggestions" div. You can avoid this problem by checking whether request.vars.month exists:
if not request.vars.month:
return '' if 'month' in request.vars else dict()
A better approach might simply be to use different functions for the search form and the suggestions given that they do completely different things and don't share any code.
if not request.vars.month also applies to the month var existing but being empty. Therefore, it's returning the form.
You need to do one of these:
Have your "suggestions" code be in a different page/file
Add a isAJAX variable to the request (or some other way to identify AJAX requests)
Check if the variable exists, rather than checking if it is falsy.
I'm trying to take user form input and display it back to the user, among other things (all of which require the input being stored as a JS variable).
I'm trying to spit it out in an alert, as a quick feedback loop, and all I keep getting is [object HTMLInputElement]. I've tried to use document.forms[0] and document.getElementById (like below) and neither work. Also, I'm using bootstrap typeahead, could that be complicating this issue?
What am I missing?
Here's the code:
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alert('you chose ' + theInput.value)"/>
<script language="JavaScript" type="Text/JavaScript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1>Input:
<script language="JavaScript" type="Text/JavaScript">
document.write(theInput.value);
</script>
</h1>
Edit: PART II, now the code works for the alert, but I need to use it elsewhere (like I said) and the variable isn't available in other sections of the html. Above, I'm just trying to get it to display that same value as a part of the html. It could be my JS, but this is pretty boilerplate stuff, so I think it's related to the location of the variable.
What do I need to do use it elsewhere? I've added the next div above to show what I'm trying.
--left an extra declaration of the variable in part II by accident, was one of the tests I was trying, removed now.
Right now, the object you're alerting is an HTML element, not a string. You can get its value using the value property:
alert('you chose ' + theInput.value)
(Note that you probably didn't mean:
var theInput = document.getElementById('txtvarInput').value;
As other answers suggest, because that would give you an empty string. It's only read once.)
You are trying to output the entire HTML-object that you have selected, not the value-property of it. Since alert() expect a string, JavaScript gives you the string representation of that object which is [object HTMLInputElement].
Try this instead:
var theInput = document.getElementById('txtvarInput').value;
var theInput = document.getElementById('txtvarInput');
should be
var theInput = document.getElementById('txtvarInput').value;
In the alert, use
theInput.value
You need to use the value property:
var theInput = document.getElementById('txtvarInput').value;
You forgot .value
Something like:
document.getElementById('txtvarInput').value
You are going to print the value of the input at the page load time. You will get an empty alert.
just do this!
<input name="submit" type="submit" class="btn" value="Select" onclick="alertVal()"/>
<script language="JavaScript" type="Text/JavaScript">
function alertVal(){
var theInput = document.getElementById('txtvarInput').value;
alert('you chose ' + theInput);
}
</script>