JavaScript, Ajax Form Submit - error on first element - javascript

I know this basic subject has been broached many times, and I have used code that has been posted from here in my own application. However, I have run into an error I just cannot resolve, and it is making me crazy. I have a form with two hidden controls (which have not been an issue in other forms), a file control, some standard input controls and a textarea ... (a sample of the form is below). When I use JavaScript (and Ajax) to try to submit it, I am getting an error that I cannot resolve:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
Form:
<form class='form form-horizontal' method='post' action='' name='attachment_form' id='attachment_form'>
<input value=1 name='event_link3' id='event_link3' hidden />
<input value=9683 name='contributor_link3' id='contributor_link3' hidden />
<div class='row'>
<!-- file upload option -->
<div class='col-lg-5 col-11'>
<div class='form-group file-upload'>
<label>Select File to Upload:</label><br />
<input type='file' class='form-control' id='attachment_file'
name='attachment_file' accept='.pdf, .mp4, .mov, .avi, .f4v'
data-toggle='tooltip' data-placement='bottom'
title='File to be uploaded should be 'standard' video or pdf format'
/>
</div> <!-- / form-group -->
</div> <!-- // col-5 -->
<div class='col-1'> <a name='attachment_clear'
onclick='attachment_clear()'
class='btn btn-primary btn-md clearButton'
data-toggle='tooltip' data-placement='bottom' title='Clear Selection'
style='margin-left: -12px !important; margin-top: 40px !important;'>
<i class='fa fa-trash' aria-hidden='true'></i></a>
</div> <!-- // col-1 -->
<div class='col-lg-6 col-12'>
<label>Web Link/URL:</label><br />
<input type='url' class='form-control'
id='web_url' name='web_url'
data-toggle='tooltip' data-placement='bottom'
title='Web address must include http:// or https:// to be valid'
/>
</div> <!-- // col-6 -->
</div> <!-- // row -->
<div class='row'>
<div class='col-lg-6 col-12'>
<label>Short Description:</label>
<input class='form-control' name='short_description' id='short_description'
data-toggle='tooltip' data-placement='bottom'
title='A short description of the file (displayed for link)' required/>
<p class='help-block'><b>Short Description is Required</b> -- the text will be used
to display as text for the file link.</p>
</div> <!-- // col-6-->
<div class='col-lg-6 col-12'>
<label>File Description:</label>
<textarea class='form-control' name='description' id='description' rows=5 required></textarea>
<p class='help-block'><b>Description is Required</b> -- Describe the file or link in as much
detail as you need ... you can also format this to some extent (see toolbar)</p>
</div> <!-- // col-12-->
</div> <!-- // row -->
<button id='attachment_submit' name='attachment_submit' class='btn btn-primary' style='margin-top: 10px;'><i class='fa fa-upload'></i> Upload Attachment</button>
</form>
The Javascript code to deal with the form is based on code I have pulled here on StackOverflow, and has been working successfully in other places. I cannot see what is different or wrong with this ...
$("#attachment_form").submit(function(e)
{
e.preventDefault();
// first thing, clear out the message div used for this (if there's anything there):
document.getElementById("attachment_message").innerHTML = "";
// validation:
var filename_check = document.getElementById( "attachment_file" ).value;
var web_url_check = document.getElementById( "web_url" ).value;
if ( filename_check == "" && web_url_check == "" )
{
alert( "You must either select a file to upload or enter a web address ..." );
return;
}
// on the flip side:
if ( filename_check != "" && web_url_check != "" )
{
alert( "You must either select a either file to upload or a web address, not both ..." );
return;
}
// get value from TinyMCE
var description = tinymce.get('description').getContent();
// make sure it's in the textarea by the same name
document.getElementById( "description" ).value = description;
// this has always worked in the past, but having issues:
var formData = new FormData(this);
// this is where the error occurs when I open the web console of my browser
I am hoping someone has experience with this and can tell me what the error is, as I am completely stumped at this point. (I have checked "this.id" in an alert to be sure I am using the correct form ...)

The FormData call probably expects a DOM element and not a jQuery element. Try passing this[0] or this.get() to get the Html element of the form.

Okay, I found my problem (thanks to the suggestion to look at the output log by Art3mix above). The issue was that I had a surrounding div tag that was also called "attachment_form" (I have a collapsible (bootstrap 4) div that is opened with a button, and I didn't even think about the fact that I had named the form the same as the div). By changing that (and references to it) to "attachment_window" instead, that resolve the whole thing. Wow. Thanks for the suggestion to look at the console output log. I seldom, if ever, look at that.

Related

Validate a form element without/before submitting the form with JavaScript

I have an HTML form that has its elements displayed in various Bootstrap modals. The first modal has a text box input that and a "Next" button to open the next modal. When the "next" button is pressed. I want to check if the text box is empty, and trigger a validation message. The form does not get submitted until the very end. Everything I've tried has not worked so far.
Javascript/jQuery code
$("#add_assistant_next").click(function () {
var textInput = document.getElementById('add_assistant_user');
var text = textInput.value;
if (text === "") {
textInput.setCustomValidity('Please fill out this field.');
textInput.checkValidity();
var form = $('#form_add_assistant');
form.find(':submit').click();
} else {
textInput.setCustomValidity('');
}
});
HTML
<form name="add_assistant" method="post" id="form_add_assistant">
<div class="modal-body">
<div class="step">
<span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
</div>
<div class="pl-3 pt-1">
<div>
<input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
<button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
</div>
<input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
</div>
</div>
... form continues in other modals
Your JS code is probably fighting with Bootstrap for control of that button. To get around that, and have your validation, you could try modifying your code to have a middle step / temporary button to help with validation first before actually submitting. So something like this:
Javascript/jQuery code
$("#my_temp_button").click(function () {
var textInput = document.getElementById('add_assistant_user');
var text = textInput.value;
// Might also want to handle null and undefined cases?
if (text === "" || text === undefined || text === null) {
// I'm assuming if it's empty, it doesn't pass validation,
// so we just display this warning and wait for the user to fix it:
textInput.setCustomValidity('Please fill out this field.');
} else {
// it's not empty so validate:
if (textInput.checkValidity()) {
// it passed validation, so ok to submit.
// call the real button:
$('#add_assistant_next').click();
// do you need this?
var form = $('#form_add_assistant');
form.find(':submit').click();
} else {
// it failed validation, so display another error?
textInput.setCustomValidity('Try again.');
}
}
});
HTML:
<form name="add_assistant" method="post" id="form_add_assistant">
<div class="modal-body">
<div class="step">
<span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
</div>
<div class="pl-3 pt-1">
<div>
<input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
<!-- Feel free to change the id name. This is the button the user sees. It's only purpose is to give your function above full control to it and prevent Bootstrap from touching it and jumping to the next modal without having the user fix the validation failure first: -->
<button type="button" id="my_temp_button" class="btn btn-outline-secondary btn">Look up user</button>
<!-- Hide the real button from the user: -->
<div style="display:none">
<button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
</div>
</div>
<input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
</div>
</div>
...
Have you tried adding a trap for the submit event itself?
$('#form_add_assistant').submit(function(evt){
//do your validation here
if (validation fails){
return false; // OR, alternatively, `evt.preventDefault()`
}
//form submission will continue if not returned false
});
References:
https://api.jquery.com/submit/
How to conduct manual form validation via jQuery .submit()

Awesome fonts and javascript search function on click

I got this script to use it as a search engine, but when I tried to change the button to replace it with a CSS styled button (including fontawesome), the button doesn't call the results. I am a newbie and my javascript knowledge is limited.
<form name="searchengine">
<input type = text name ="keywords" placeholder ="Search..." style ="font-size:14px;hight:35px;width:240px;" value="" maxlength=40>
<input type = button name="go" Value=" 🔍 " style ="height:30px;width:35px;" onClick="search()">
</form>
I just adjusted the inline styling but I would like to replace it with this:
<form name="searchengine">
<input type="hidden" name="keywords" value="1">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<div class="box">
<div class="container-4">
<input type="search" id="keywords" placeholder="Search..." />
<button class="icon"><i class="fa fa-search"></i></button>
</div>
</form>
I know that there is no onclick function assigned on the second example but I have searched everywhere and couldn't find an answer, I have tried different ways to make it "clickable" but with no success. Below are some examples of what I have done. Most come from Stackoverflow.
<span onClick="myFunction()"><i class="fa fa-search"></i></span>
<i class="fa fa-search" onclick="search()"></i>
Thanks in advance for your help. Please let me know if you require the full script.
Here is the entire script. Thanks for your help.
<html>
<title>
Search Engine
</title>
<head>
<script>
title = new Object();
desc = new Object();
links= new Object();
matched= new Object();
keywords= new Object();
found= new Object();
var temp=0;
// actual location or the item to be searched // description of he location
// actual link
// percentage match found
// keywords as parsed from the input
// # of titles present in the database
title[0]=14
//no of keywords after parsing
keywords[0]=0
//no of matches found.
found[0]=0
<!-- Begin List of Searchable Items -->
<!--put the list of the links and descriptions here!!-->
title[1]="Introduction FAQs Java JavaScript beginner"
desc[1]="JavaScript Primer (Part 1 of 2) "
links[1]="http://www.javascriptkit.com/primer1.htm"
matched[1]=0
title[2]="objects document function parameter last modified date"
desc[2]="JavaScript Primer (Part 2 of 2) "
links[2]="http://www.javascriptkit.com/primer2.htm"
matched[2]=0
title[3]="alert confirm prompt box pop up dialog"
desc[3]="Creating Alert, Confirm, and Prompt Boxes"
links[3]="http://www.javascriptkit.com/alert.htm"
matched[3]=0
title[4]="event handler onClick onLoad onMouseover onMouseout onUnload"
desc[4]="Understanding Event Handlers in JavaScript"
links[4]="http://www.javascriptkit.com/event.htm"
matched[4]=0
title[5]="object model tree accessing forms "
desc[5]="Accessing and Validating Forms Using JavaScript (Part 1 of 2)"
links[5]="http://www.javascriptkit.com/form1.htm"
matched[5]=0
title[6]="form validation onBlur onSubmit"
desc[6]="Accessing and Validating Forms Using JavaScript (Part 2 of 2)"
links[6]="http://www.javascriptkit.com/form2.htm"
matched[6]=0
title[7]="date object write html setTimeout function"
desc[7]="Creating Time Dependent Scripts using JavaScript (Part 1 of 2)"
links[7]="http://www.javascriptkit.com/time1.htm"
matched[7]=0
title[8]="live clock watermark"
desc[8]="Creating Time Dependent Scripts using JavaScript (Part 2 of 2)"
links[8]="http://www.javascriptkit.com/time2.htm"
matched[8]=0
title[9]="image preload rollover effect filter"
desc[9]="Images and JavaScript- Apples and Apples (Part 1 of 2)"
links[9]="http://www.javascriptkit.com/image1.htm"
matched[9]=0
title[10]="rollover effect"
desc[10]="Images and JavaScript- Apples and Apples (Part 2 of 2)"
links[10]="http://www.javascriptkit.com/image2.htm"
matched[10]=0
title[11]="new window open secondary reload close toolbar menubar status bar "
desc[11]="Windows and JavaScript"
links[11]="http://www.javascriptkit.com/window.htm"
matched[11]=0
title[12]="frames access object multiple"
desc[12]="Loading Two frames with one link."
links[12]="http://www.javascriptkit.com/twoframes.htm"
matched[12]=0
title[13]="selection list options array text vale"
desc[13]="I'll hava a double combo please (Part 1 of 2)"
links[13]="http://www.javascriptkit.com/combos1.htm"
matched[13]=0
title[14]="combo link box jump"
desc[14]="I'll hava a double combo please (Part 2 of 2)"
links[14]="http://www.javascriptkit.com/combos2.htm"
matched[14]=0
<!-- End list of Searchable items -->
function search(){
// get the input from the input by the user and strip it into keywords //
var skeyword=document.searchengine.keywords.value.toLowerCase();
var check=1;
var pos=0;
var i=0;
var j=0;
var itemp=0;
var config='';
while (true)
{
if (skeyword.indexOf("+") == -1 )
{
keywords[check]=skeyword;
break;
}
pos=skeyword.indexOf("+");
if (skeyword !="+")
{
keywords[check]=skeyword.substring(0,pos); check++;
}
else
{
check--;
break;
}
skeyword=skeyword.substring(pos+1, skeyword.length);
if (skeyword.length ==0)
{
check--;
break;
}
}
// the keywords have been put in keywords object.
keywords[0]=check;
//alert(check);
// matching and storing the matches in matched
for ( i=1; i<=keywords[0];i++)
{
for (j=1;j<=title[0];j++)
{
if (title[j].toLowerCase().indexOf(keywords[i]) > -1 )
{
matched[j]++;
}
}
}
// putting all the indexes of the matched records in found
for (i=1;i<=title[0];i++)
{
if (matched[i] > 0 )
{
found[0]++;
// increment the found
found[found[0]]=i;
}
}
//alert("found 0 " + found[0]);
// sort the list as per max percentage of matches
for (i=1;i<=found[0]-1;i++)
{
for(j=i+1;j<=found[0];j++)
{
if ( matched[found[i]]< matched[found[j]] )
{
temp= found[j];
found[j]=found[i];
found[i]=temp;
}
}
}
config='toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes'
output = window.open ("","outputwindow",config)
output.document.write('<title> Atlantis Direct Search Result </title>');
output.document.write('<BODY bgcolor=#ffffff text=#000000 link=#990099 vlink =#339966 >');
output.document.write('<center> <h1> Search Results </h1></center>');
output.document.write('<hr>');
output.document.write(' The Keyword(s) you searched :: '.big() );
for (i=1; i<=keywords[0]; i++)
{
output.document.write( keywords[i].bold() +" "); }
output.document.write('<br>');
if (found[0]==0)
{
output.document.write('<hr>');
output.document.write("<b>No matches resulted in this search </b> <br>");
output.document.write("You may close the results and reduce the length/number of the keywords <br>");
}
else
{
output.document.write(" <hr> <b> The Results of the search are : </b> ");
output.document.write( found[0] +" Entries found ".italics());
output.document.write("<table border=1 width=100%>");
for (i=1; i<=found[0];i++)
{
output.document.write("<tr><td valign=topbgcolor=#9999ff>");
output.document.write("<h3>" +i +"</h3>"); output.document.write("<td valign=top>");
itemp=found[i];
output.document.write(desc[itemp].bold() +"<br>" +links[itemp].link(links[itemp])+"<br>");
temp= (matched[itemp]/keywords[0])*100
output.document.write("<i> Matched with keywords :: "+temp+" % </i>" );
matched[itemp]=0
}
found[0]=0;
output.document.write("</table>");
}
output.document.write ('This search was created by &copy Satadip Dutta 1997'); output.document.write ("<hr>");
output.document.write ("<form><center>");
output.document.write ("<input type='button' value='Start Another Search' onClick = 'self.close()'>") ;
output.document.write ("</center></form>");
output.document.close();
}
</script>
<head>
<body bgcolor="#ffffff">
<center>
<H1>Search Engine</H1>
</center>
<hr>
This is a search engine implemented in Javascript. You will need a
Java Script enabled browser to run this search.
<hr>
<P>
</P>
<TABLE BORDER=0 CELLSPACING=5 CELLPADDING=5>
<TR>
<TD WIDTH="20%" ALIGN="left">
This search is NOT case sensitive.
</TD>
<TD WIDTH="80%" ALIGN="left">
Put "+" between keywords in a list if using more than one keywords.
</TD>
</TR>
</TABLE>
<form name="searchengine">
<center>
Keywords:
<input type = text name ="keywords" placeholder ="Search..." value="" maxlength=40>
<input type = button name="go" Value="Go ahead and find" onClick="search()">
<br>
</center>
</form>
<hr>
<!-- you can write more text/instructions out here. -->
</body>
<html>
Some points to consider:
You forgot to set the type of your button to submit
Links are normally place on the <head>
You should give your form an action
<head>
...
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
...
</head>
...
<form name="searchengine" action="doSomething">
<input type="hidden" name="keywords" value="1">
<div class="box">
<div class="container-4">
<input type="search" id="keywords" placeholder="Search..." />
<button type="submit" class="icon"><i class="fa fa-search"></i></button>
</div>
</div>
Hope it helps.
This code works just fine. Your link is messed up, why is it just // instead of https://? Your links should be in the head, if they aren't they aren't loaded before the body, which causes a split second of unstyled content to show before it reaches the stylesheet. Your form should have an action to perform and your search button should be of the type submit so it's a submit button for the form.
The below code and jsfiddle work just fine if you want to try them out.
Also, Dreamweaver is not that impressive, I recommend getting Netbeans instead, it does the same job but for free (all you really want from your web IDE is code completion so you don't have to write as much, and both Netbeans and Dreamweaver does this equally well except that Netbeans is better for more all-around programming for all kinds of languages).
https://jsfiddle.net/vfmrc40k/
<html>
<head>
<!-- Links go in the head, they are not scripts and this makes them load before the body so that you don't get a split second of unstyled content showing -->
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<script>
function performSearch () {
alert('I am searching!')
// Use e.g. jQuery to get the value for the search box, it's easiest
}
</script>
</head>
<body>
<!-- Your form should have an action to perform, in this case a javascript function. It isn't just 'correct', it also makes it possible to press Enter to perform the search, because enter and the submit button both trigger the forms action. -->
<form name="searchengine" action="javascript:performSearch()">
<input type="hidden" name="keywords" value="1">
<div class="box">
<div class="container-4">
<input type="search" id="keywords" placeholder="Search..." />
<button type="submit" class="icon"><i class="fa fa-search"></i></button>
</div>
<!-- You forgot a </div> -->
</div>
</form>
</body>
</html>

Change form input field value with jquery within a bootstrap modal

I have a form within a bootstrap modal. I would like the input fields to display the past values that the user entered the first time they filled out the form, which I am retrieving from a cloudant database. I would like these input fields to be editable so that the user can resubmit the form with any changes they may have. However, I am stuck when trying to display the past information in the input fields. I can't find any reason why these value of the input fields are not being changed.
The javascript that adds my buttons to my boostrap list-group:
var loadIotPanel = function(iotsJSON)
{
for(var iot in iotsJSON)
{
var button = $('<button/>').text(iotsJSON[iot].appID).addClass('list-group-item iot').attr({name:iotsJSON[iot].appID, "aria-label": "Quick View IoT", "data-toggle": "modal", "data-target": "#quick-view-iot-modal", type: "button"});
$('#iot-list').append(button);
}
};
The html where my button will be placed within my list-group:
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12 col-sm-12 dash-col">
<button name="edit-iots" aria-label="Edit IoTs" data-toggle="modal" data-target="#edit-iots-modal" type="button" class="icon"><span class="glyphicon glyphicon-edit gray"></span></button>
<p class="fancy-font dash-item-title">Your IoTs</p>
<button name="add-iot" aria-label="Add IoT" data-toggle="modal" data-target="#connect-iot-modal" type="button" class="icon"><span class="glyphicon glyphicon-plus gray"></span></button>
<div class="list-group iot" id="iot-list"><!-- buttons will be placed here --></div>
</div>...
The modal that pops up when clicking a button:
<div class="modal fade" id="quick-view-iot-modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="quick-view-iot-h4"></h4>
</div>
<div class="modal-body">
<form id="edit-iot-form" method="post">
IoT Name: <br>
<input type="text" name="iot-name" class="iot-value" required><br>
Organization ID: <br>
<input type="text" name="org-id" class="iot-value" readonly required><br>
Authentication Method: <br>
<input type="text" name="auth-method" class="iot-value" value="apikey" readonly><br>
API Key: <br>
<input type="text" name="api-key" class="iot-value" readonly required><br>
Authentication Token: <br>
<input type="text" name="auth-token" class="iot-value" readonly required><br>
</form>
<button name="more" type="button" class="fancy-font page-button">More</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
The javascript that adds the content to modal. It is within a main method that is called when document is ready:
$('.iot').click(
function()
{
var iotName = event.target.name;
getIots(loadIotQuickView, iotName);
$('h4#quick-view-iot-h4.modal-title').text(event.target.name);
});
The getIots() function: (it includes parameter variable=null because I also use it in another part of code where the varaible parameter is not used. This method sends an ajax post to a servlet, which then responds with an array of iot objects)
var getIots = function(callback, variable=null)
{
var iotsJSON = null;
$.post("DashboardServlet", {loadIotPanel: "true"}, function(response)
{
iotsJSON = response;
callback(response, variable);
});
The loadIotQuickView() function: (This is where I believe I am getting problems)
var loadIotQuickView = function(iotsJSON, iotName)
{
var currentIoT = null;
for(var iot in iotsJSON)
{
if(iotsJSON[iot].appID = iotName)
currentIoT = iotsJSON[iot];
}
if(currentIoT == null)
return;
$('.iot-value[name="iot-name"]').attr("value",currentIoT.appId);
};
I've tried numerous jquery selectors but none of the input field values within the form will change. I've stepped through the code and all of my variables have the correct values that its just the last line that's not executing how I want. I am unsure if there is an issue with my jquery selector or if it is something else. Thanks in advance!
UPDATE:
I've tried the following selectors:
$('.iot-value[name="iot-name"]')
$('input[name="iot-name"]')
$('.iot-value')
$('#connect-iot-modal').find('input[name="iot-name"]')
I've also tried adding an id of "edit-iot-name" to my input field:
$('#edit-iot-name')
$('#connect-iot-modal #edit-iot-name')
But none of these have worked, which leads me to believe that it must not be an issue with my selector.
UPDATE:
I've also tried using .val(currentIoT.appID) with all of the previous selectors. Still not working.
I'm not sure why, but adding the id of the modal that my form is in, which is #quick-view-iot-modal, to my selector worked. However for some reason it only works when I use .val() and not when I use .attr(). So the final result is:
$('#quick-view-iot-modal #edit-iot-name').val(currentIoT.appID);
I'm not sure why it is required to add the id of the modal, and I'm not sure why it doesn't work like this:
$('#quick-view-iot-modal #edit-iot-name').attr("value",currentIoT.appID);
But it works! If anyone knows why it only works with this combination, please let me know!
try:
$('.iot-value[name="iot-name"]').val(currentIoT.appId);
Your selector is pretty weird as well. why not just refer to the input by name?
$('input[name="iot-name"]').val(currentIoT.appId);
In your code here:
$('.iot-value[name="iot-name"]')
"iot-name" is a string literal, and it will not evaluate to the value of your iot-name variable.
I'm guessing that you are looking to use the variable's value in your selector, which would look like this:
$('.iot-value[name="' + iot-name + '"]')
I have been struggling with this problem for 3 hours. The realisation that you must reference the object through the modal div is the winner.
I was trying to do 2 things:
populate the href in an <a> button on my modal
set the value of another field using an onChange()
so I end up with:
$("#modal-form #linkbtn").attr("href", url);
$('#modal-form #inputfield").val(newVal);
Thanks so much for this hint.
LISTEN!
i've got a good solution for all of you guys!
$("#exampleModal").modal("show");
$(function () {
$("#exampleModal #ticket_id").val("your_value_variable");
});
try this way after you load your modal show it then use DOM ready event then set your value to it input text and amazingly it works! this is the easiest and simplest way from me

Simple jQuery code doesn't work (dealing with Objects)

All right. So I'm coding after A LOOONG TIME, and I just went on to codecademy to get a bit refreshed with javascript. So I learnt something I didn't know before : OOP.
Help. I tried something. Will include the JSfiddle. But I don't know why, it doesn't work.
Nevermind my Idiocy, I will complete the code as soon as I know what the problem in the prev code was. I have alot to do in that. I also want to learn PHP to make a kind of phone directory!
I have also NOT included the CSS, but that hardly matters.
What the code should do, is that everytime a user fills up the form and clicks submit, it should append the values in a '#results' div. Not doing anything. Help?
Also, nevermind the two password fields. I will write the code for validating the form once I am clear with this problem.
THANK YOU IN ADVANCE.
JSFIDDLE : http://jsfiddle.net/Ns66V/1/
HTML -- >
<html>
<head>
<link rel="stylesheet" href='style.css'>
<script type="type/javascript" src='jquery.js'></script>
<script type="type/javascript" src='js.js'></script>
<title>Form JS</title>
</head>
<body>
<div class='container'>
<h1>Create an ID! It's absolutely <strong>FREE!</strong></H1>
<div id='form'><form action='get'>
<input name='fname' type='text' placeholder='First Name'><br>
<input name='lname' type='text' placeholder='Last Name'><br>
<input name='email' type='email' placeholder='Email Address'><br>
<input name='passw' type='password' placeholder='Password'>
<input name='Again' id='last' type='password' placeholder='Again!'><br>
<select name='gender'>
<option value='male'>Male</option>
<option value='female'>Female</option>
<option value='other'>Other</option>
</select>
<div id='submit'><strong>SUBMIT IT!</strong></div>
</form>
</div>
<div class='results'>
<div class='vals' id='intro'>
<div class='srn item'>#</div>
<div class='bigitem item'>FULL NAME</div>
<div class='bigitem item'>EMAIL ADDRESS</div>
<div class='gender item'>Gender</div>
</div>
<div class='vals'>
<div class='srn item'>#</div>
<div class='bigitem item'>FULL NAME</div>
<div class='bigitem item'>EMAIL ADDRESS</div>
<div class='gender item'>Gender</div>
</div>
</div>
</div>
</body>
</html>
JS (JQuery) -->
$(document).ready(function(){
function Person(fname,lname,email,passw,gend){
this.fname = fname;
this.lname = lname;
this.email = email;
this.passw = passw;
this.gend = gend;
};
var numPeople = 0; //Setting the number of people var.
$('#submit').click(function(){
var fname = $('input[name=fname]').val(), //SETS VALUES OF ALL THE INPUTS
lname = $('input[name=lname]').val(), //SETS VALUES OF ALL THE INPUTS
email = $('input[name=email]').val(), //SETS VALUES OF ALL THE INPUTS
passw = $('input[name=passw]').val(), //SETS VALUES OF ALL THE INPUTS
gend = $('select[name=gender]').val(); //SETS VALUES OF ALL THE INPUTS
var People = new Array(); //Definin
numPeople++;
People[numPeople] = new Person(fname,lname,email,passw,gend);
$('.results').append(People[numPeople].fname + People[numPeople].lname + People[numPeople].email + People[numPeople].passw + People[numPeople].gend);
}); //#SUBMIT.CLICK() END
});
OOP isn't entirely needed in this case. The problems is that you need to use #results, and you need to close your button along with other tags.
HTML
<button id='submit' type='button'><strong>SUBMIT IT!</strong></button>
JS
$('#results').append(...);
Here is a Fiddle example, added a <br /> at the end.
Also get and post are for a forms method attribute. action is where the form sends the data. So you probably want:
<form method="get"></form>
Check http://jsfiddle.net/Ns66V/4/
The button tag was not closed and the content was appended to the button and
$('#submit').click(function()
should be replaced with
$('#submit').on('click', function()
Now seems to work.
Of course you should improve how you append the content though - use html tags to separate each information.

Captcha IMG/Numbers Combination

I'm trying to create a Captcha in JavaScript but I ran into issues. I want the CAPTCHA to display at random, one of the declared images and then validate users input against the text on the images. So far, I have the Code below and it doesn't show anything:
<script type="text/javascript">
var "<img src="images/ci0.jpg" />" = 56777;
var "<img src="images/ci1.jpg" />" = 67646;
var "<img src="images/ici2.jpg" />" = 77666;
var code = ci0, ci1, ci2;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
</script>
HTML
<div id="left">
<label for="code">Enter code next <span id="txtCaptchaDiv" style="color:#F00"></span><br />
<!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label>
</div><!-- End Left -->
<div id="righty">
<span id="spryconfirm1">
<label>
<input type="text" name="checker" id="checker" />
</label>
<span class="confirmRequiredMsg">You must enter the Code.</span><span class="confirmInvalidMsg">The values don't match.</span></span>
</div><!-- End righty -->
</div>
By the way I see it you should use reCAPTCHA since you still have a long way to go before creating a CAPTCHA validator yourself. This is not only a matter of client-side but also server-side which you are already ignoring.
Get a reCAPTCHA embed code and use it in your HTML.

Categories