I've a script:
<form id="myform">
<input type="text" value="" id="input1">
<input type="text" value="" id="input2">
<input type="submit" value="submit">
</form>
<img id="image" src="http://mydomain.com/empty.gif" />
<script>
$(document).ready(function () {
$("#myform").submit(function (ev) {
ev.preventDefault();
var val1 = $("#input1").val();
var val1 = $("#input2").val();
$("#image").attr("src", "http://mydomain.com/image?val1="+val1+"&val2="+val2);
});
});
</script>
How would it look like if written in JavaScript?
<img id="image" src="http://mydomain.com/empty.gif" />
<script>
window.onload = function() { // Not all browsers support DOMContentLoaded
document.getElementById("myform").onsubmit = function() {
var val1 = document.getElementById("input1").value;
var val2 = document.getElementById("input2").value;
document.getElementById("image").src="http://mydomain.com/image?val1="+val1+"&val2="+val2;
return false;
};
};
</script>
If you NAME the fields you can use
window.onload = function() {
document.getElementById("myform").onsubmit = function() {
document.getElementById("image").src="http://mydomain.com/image?val1="+this.input1.value+"&val2="+this.input2.value;
return false;
};
};
You MAY want to escape the two values
Related
Hi everyone I'm creating an database using indexed db in Angular js. My task is to save the data into database and my question is can we use multiple ng-model in one function ? Let me show you my code to make it clear.
index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#3.1.1" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script data-require="angular.js#1.2.13" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script data-require="angular.js#1.2.13" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular-animate.js"></script>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body>
<div data-ng-app="indexDBSample" data-ng-controller="TodoController as vm">
<table>
<tr data-ng-repeat="todo in vm.todos">
<td>{{todo.text}}</td>
<td>[X]</td>
</tr>
</table>
<br />
<input type="text" data-ng-model="vm.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
<input type="button" value="Add" data-ng-click="vm.addTodo()" />
<input type="button" value="Refresh" data-ng-click="vm.refreshList()" />
</div>
</body>
</html>
script.js
var app = angular.module('indexDBSample', []);
app.factory('indexedDBDataSvc', function($window, $q){
var indexedDB = $window.indexedDB;
var db=null;
var lastIndex=0;
var open = function(){
var deferred = $q.defer();
var version = 1;
var request = indexedDB.open("todoData", version);
request.onupgradeneeded = function(e) {
db = e.target.result;
e.target.transaction.onerror = indexedDB.onerror;
if(db.objectStoreNames.contains("todo")) {
db.deleteObjectStore("todo");
}
var store = db.createObjectStore("todo",
{keyPath: "id"});
};
request.onsuccess = function(e) {
db = e.target.result;
deferred.resolve();
};
request.onerror = function(){
deferred.reject();
};
return deferred.promise;
};
var getTodos = function(){
var deferred = $q.defer();
if(db === null){
deferred.reject("IndexDB is not opened yet!");
}
else{
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
var todos = [];
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(result === null || result === undefined)
{
deferred.resolve(todos);
}
else{
todos.push(result.value);
if(result.value.id > lastIndex){
lastIndex=result.value.id;
}
result.continue();
}
};
cursorRequest.onerror = function(e){
console.log(e.value);
deferred.reject("Something went wrong!!!");
};
}
return deferred.promise;
};
var deleteTodo = function(id){
var deferred = $q.defer();
if(db === null){
deferred.reject("IndexDB is not opened yet!");
}
else{
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
var request = store.delete(id);
request.onsuccess = function(e) {
deferred.resolve();
};
request.onerror = function(e) {
console.log(e.value);
deferred.reject("Todo item couldn't be deleted");
};
}
return deferred.promise;
};
var addTodo = function(todoText){
var deferred = $q.defer();
if(db === null){
deferred.reject("IndexDB is not opened yet!");
}
else{
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
lastIndex++;
var request = store.put({
"id": lastIndex,
"text": todoText
});
request.onsuccess = function(e) {
deferred.resolve();
};
request.onerror = function(e) {
console.log(e.value);
deferred.reject("Todo item couldn't be added!");
};
}
return deferred.promise;
};
return {
open: open,
getTodos: getTodos,
addTodo: addTodo,
deleteTodo: deleteTodo
};
});
app.controller('TodoController', function($window, indexedDBDataSvc){
var vm = this;
vm.todos=[];
vm.refreshList = function(){
indexedDBDataSvc.getTodos().then(function(data){
vm.todos=data;
}, function(err){
$window.alert(err);
});
};
vm.addTodo = function(){
indexedDBDataSvc.addTodo(vm.todoText).then(function(){
vm.refreshList();
vm.todo="";
}
, function(err){
$window.alert(err);
});
};
vm.deleteTodo = function(id){
indexedDBDataSvc.deleteTodo(id).then(function(){
vm.refreshList();
}, function(err){
$window.alert(err);
});
};
function init(){
indexedDBDataSvc.open().then(function(){
vm.refreshList();
});
}
init();
});
I have used three ng-model with three different input field but what i need is to use all the three ng-model in one function i.e in
vm.addTodo = function(){
indexedDBDataSvc.addTodo(vm.todoText).then(function(){
vm.refreshList();
vm.todo="";
}
, function(err){
$window.alert(err);
});
};
to get three different output.Please help me with this because i'm new to angular.js
And here is my plunker :http://plnkr.co/edit/3yM2j9Dgv5FzEP2L9pYH?p=preview
Bind the input in the form as:
<form name="my_form">
<input type="text" data-ng-model="vm.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
<input type="text" data-ng-model="vm.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
<button type="button" value="Add" data-ng-Click="vm.addTodo(vm)">Add</button>
<button type="button" value="Refresh" data-ng-Click="vm.refreshList()">Refresh</button>
</form>
In the app.js, in your function, you get all your data from data-ng-model.
vm.addTodo = function(vm){
alert(angular.toJson(vm));
console.log(angular.toJson(vm.todoText));//check the value in console
console.log(angular.toJson(vm.todoText1));
console.log(angular.toJson(vm.todoText2));//you can use the value as vm.todoText,vm.todoText1 and so on.
indexedDBDataSvc.addTodo(vm.todoText).then(function(){
vm.refreshList();
vm.todo="";
}
, function(err){
$window.alert(err);
});
};
The rest of the logic depends upon whatever you do with the data.
Updates: As per your need of comment.Check your addition of data using your refresh button.Passing the vm as in the original code, created conflict in the controller section so i changed the ng-model to form so that i could get the exact model value.
<form name="my_form">
<input type="text" data-ng-model="form.todoText" name="todo" placeholder="textbox1" style="width: 200px;" />
<input type="text" data-ng-model="form.todoText1" name="todo" placeholder="textbox2" style="width: 200px;" />
<input type="text" data-ng-model="form.todoText2" name="todo" placeholder="textbox3" style="width: 200px;" />
<button type="button" value="Add" data-ng-Click="vm.addTodo(form)">Add</button>
<button type="button" value="Refresh" data-ng-Click="vm.refreshList()">Refresh</button>
</form>
app.js
vm.addTodo = function(vm){
angular.forEach(vm,function(key,value){
indexedDBDataSvc.addTodo(key).then(function(){
$window.location.reload();
vm.todo="";
}
, function(err){
$window.alert(err);
});
});
};
Checkout this plunkr: http://plnkr.co/edit/xyR2W1GpylMXofIKi1BR?p=preview
I've tried a lot of things but I can't seem to make it work
Problem is whatever I type is considered false, even when I try valid email adress (such as ok#gmail.com)
Here's my code
function validateEmail(email) {
var re = /[^\s#]+#[^\s#]+\.[^\s#]+/;
return re.test(email);
}
var email = $('input[name = pEmail]').val();
$('#nPopupSubmit').click(function () {
if (!validateEmail(email)) {
$('label[id = pEmailError]').show();
$('input[name = pEmail]').focus();
return false;
} else {
whatever
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form id="popup1" method="post">
<fieldset>
<input id="pEmail" type="text" placeholder="E-mail" value="E-mail" onclick="this.value=''" class="popup_input" name="pEmail" type="text" />
<label id="pEmailError" style="color:#FF0000; display:none;">Error</label>
<button type="submit" id="nPopupSubmit" name="nPopupSubmit">Go !</button>
</fieldset>
</form>
Do any of you have a clue on what's going on ?
Thank you !
Your function doesn't contain error, perhaps your jQuery? Your email variable should be defined after the click, otherwise, email's value would always = "Email" (the default value)
$('#nPopupSubmit').click(function () {
var email = $('#pEmail').val(); //<-- This is where you should put this
if (!validateEmail(email)) {
$('#pEmailError').show();
$('#pEmail').focus();
return false;
} else {
//whatever
}
});
Also, you can simplify your code by using the ids you have already given your elements :)
function validateEmail(email) {
var re = /[^\s#]+#[^\s#]+\.[^\s#]+/;
return re.test(email);
}
$('#nPopupSubmit').click(function () {
var email = $('#pEmail').val();
if (validateEmail(email) !== true) {
$('#pEmailError').show();
$('#pEmail').focus();
return false;
} else {
//whatever
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="popup1" method="post">
<fieldset>
<input id="pEmail" type="text" placeholder="E-mail" value="E-mail" onclick="this.value=''" class="popup_input" name="pEmail" type="text" />
<label id="pEmailError" style="color:#FF0000; display:none;">Error</label>
<button type="submit" id="nPopupSubmit" name="nPopupSubmit">Go !</button>
</fieldset>
</form>
Your current regex won't validate how you want.
You can try this:
function validateEmail(email) {
var re = new RegExp("^[^\\s#]+#[^\\s#]+?\\.[^\\s#]+$", "m");
console.log(email.match(re));
if(email.match(re))
{
return true;
}
else
{
return false;
}
}
window.alert(validateEmail("a#b.c"));
window.alert(validateEmail("a #b.c"));
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script>
function validateEmail(email) {
var re = new RegExp("^[^\\s#]+#[^\\s#]+?\\.[^\\s#]+$", "m");
console.log(email.match(re));
if(email.match(re))
{
return true;
}
else
{
return false;
}
}
console.log(validateEmail("a#b.c"));
</script>
</body>
</html>
Hope that helps. If you have any questions on specifics just let me know...
So I have been messing around with dynamic input fields and everything is working great. The only issue I'm having is stopping the first input_line from being deleted.
So pretty much every input_line (refer to my fiddle for exmaple) should be able to be removed except the first one, that one should always stay.
Illustration:
Any suggestions how I can achieve this?
HTML:
<form action="javascript:void(0);" method="POST" autocomplete="off">
<button class="add">Add Field</button>
<div class='input_line'>
<input type="text" name="input_0" placeholder="Input1"><input type="button" class="duplicate" value="duplicate"><input type="button" class="remove" value="remove">
</div>
</form>
jQuery:
$(document).ready(function () {
'use strict';
var input = 1,
blank_line = $('.input_line');
$('.add').click(function () {
var newElement = blank_line.clone(true).hide();
$('form').append(newElement);
$(newElement).slideDown();
});
$('form').on('click', '.duplicate', function () {
$(this).parent().clone().hide().insertAfter($(this).parent().after()).slideDown();
$('.input_line').last().before($('.add'));
input = input + 1;
});
$('form').on('click', '.remove', function () {
$(this).parent().slideUp(function () {
$(this).remove();
});
$('.input_line').last().before($('.add'));
input = input - 1;
});
});
JSFiddle
Any help would be greatly appreciated!
Hide the remove when there's one row, else show it:
http://jsfiddle.net/gqgaswdy/23/
$(document).ready(function () {
'use strict';
var input = 1,
blank_line = $('.input_line');
var removing = false;
$('.remove').hide();
$('.add').click(function () {
var newElement = blank_line.clone(true).hide();
$('form').append(newElement);
$(newElement).slideDown();
$('.remove').show();
});
$('form').on('click', '.duplicate', function () {
$(this).parent().clone().hide().insertAfter($(this).parent().after()).slideDown();
$('.input_line').last().before($('.add'));
$('.remove').show();
input = input + 1;
});
$('form').on('click', '.remove', function () {
if (removing) {
return;
} else {
if ($('.input_line').length <= 2) $('.remove').hide();
$(this).parent().slideUp(function () {
$(this).remove();
removing = false;
});
$('.input_line').last().before($('.add'));
input = input - 1;
}
removing = true;
});
});
Just would like to show you how easy it is to create such behavior in frameworks actually intended for databinding (which jquery is not, so you have to write a lot of additional/unnecessary logic) with example of knockout.js
Demo
<div data-bind="foreach: rows">
<div>
<input type="text" data-bind="value: $data.name">
<button data-bind="click: $root.duplicate">Duplicate</button>
<button data-bind="click: $root.remove, enable: $root.rows().length > 1">Remove</button>
</div>
</div>
<button id="button" data-bind="click: addRow">add Row</button>
var row = function(name) {
this.name = ko.observable(name);
};
function TableModel() {
var self = this;
self.rows = ko.observableArray([]);
self.addRow = function() {
self.rows.push( new row('') );
};
self.duplicate = function(a) {
self.rows.push( new row(a.name()) );
};
self.remove = function(a) {
self.rows.remove(a);
};
}
ko.applyBindings(new TableModel());
Maybe add new function like this:
function HideRemoveButton(){
if($('.input_line').length <= 1){
$('.remove').hide()
}
else{
$('.remove').show()
}
}
I've tried working with some code from JSFiddle, and it is working fine.
Although when I try and implement it in HTML, it doesn't work the same way.
Here's what I have so far:
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
HTML:
<h1>Button should be enabled if at least one checkbox is checked</h1>
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " disabled/>
You need to wrap the script inside window.onload event to make sure that the dom elements are available.
window.onload = function() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked) sendbtn.disabled = true;
else sendbtn.disabled = false;
}
}
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
Your javascript needs to be in <script> tags. It's not clear if they are or not by your question, so I'll assume they're not:
<html>
<head><title>Still learning</title></head>
<body>
<script type="text/javascript">
window.onload = function() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
};
</script>
<h1>Button should be enabled if at least one checkbox is checked</h1>
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " disabled/>
</body>
</html>
Read up on html basics
This one: Uncaught TypeError: Cannot set property 'onchange' of null
Your javascript is executing before the html finishes completely loading.
This is why document.getElementById('checkme') is returning null. Put the function into a window.onload and insert the script into the <head> like this.
<html>
<head><title>Still learning</title>
<script>
window.onload = function() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
};
</script>
</head>
<body>
<h1>Button should be enabled if at least one checkbox is checked</h1>
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " disabled/>
</body>
</html>
It should work now. See this fiddle: http://jsfiddle.net/brbcoding/n9z5D/
I am new to jquery and i think this is just a basic problem. `
<input type="text" name="text1" value=""></input>
<input type="text" name="text2" value=""></input>
<input type="text" name="text3" value=""></input>
<input type="text" name="text4" value=""></input>
<input type="text" name="text5" value=""></input>
<input type="submit" value="submit"></input>
<pre id="result">
</pre>
</form>`
This is my html form and i am using following jquery function to produce json object
$.fn.serializeObject = function()
{
var o = {};
var d={};
var a = this.serializeArray();
$.each(a, function(i,n) {
o['name'] = n['name'];
o['content'] =(n['value']);
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
on runnig the above html i am getting the output {"name":"text5","content":"sdsd"}
just the final text field. i know am wrong somewhere . can someone help me to fix it. thanks in advance
That's because you are overwriting object's properties and the last values win, you can use an array and it's push method.
$.fn.serializeObject = function () {
var o = [];
var a = this.serializeArray();
$.each(a, function (i, n) {
o.push({
name: n['name'],
content: n['value']
})
});
return o;
};
http://jsfiddle.net/kxM3e/
Using jQuery map method:
$.fn.serializeObject = function () {
return this.find('input, textarea, select').map(function(){
return { name: this.name, content: this.value };
}).get();
};