I get "undefined" print 3 times (the right amount of times). How can I get the data-bind value for the found inputs?
function DataBindForEdit(dataTag, controller, action) {
// get the inputs that will be sent to the controller
var dataBoundControls = $('[data-bind="' + dataTag + '"] [data-bind]');
// loop over each element
dataBoundControls.each(function () {
var self = $(this);
// for now just print out the value of the data-bind attribute
alert(self.data("data-bind"));
});
}
#section Scripts{
<script>
$(function () {
$("#btnSave").click(function(){
DataBindForEdit("Customer", "Index", "CreateCustomers");
});
});
</script>
}
<form data-bind="Customer">
Name: <input type="text" data-bind="Name" data-bind-type="text" />
Birthday: <input type="text" data-bind="Birthday" data-bind-type="text" />
Address: <input type="text" data-bind="Address" data-bind-type="text" />
<input type="submit" value="Save" id="btnSave" />
</form>
You should not include data-. It should be:
self.data("bind")
Related
<form id="contact-form">
<input type="text" value="100" id="number" name="number" />
<input type="hidden" value="00" id="decimal" name="decimal" />
<input type="submit" name="submit-form" />
</form>
<script>
var form = document.getElementById('#contact-form');
form.addEventListener("submit", function() {
var input = document.createElement('number');
input.type = 'text';
input.name = 'decimal';
input.value = '00';
this.appendChild(input);
}, true);
</script>
// I want it to append the decimal '00' to the input number before submitting the form.
// I want the result as = 10000
form.addEventListener("submit", function() {
var decimal_val= document.getElementByName('decimal').value;
var number= document.getElementByName('number').value;
number = decimal_val+number;
}, true);
try this
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<form id="contact-form">
<input type="text" value="100" id="number" name="number" />
<input type="hidden" value="00" id="decimal" name="decimal" />
<input type="submit" name="submit-form" id="clickme" />
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){
//in here ,first check the existing value with an alert when document is ready
var hiddenValue = $("#decimal").val();
alert("before value :" + hiddenValue);
//in this part you can assign the new value
$("#clickme").click(function(){
var newhiddenVal = "new decimal";
$("#decimal").val(newhiddenVal);
var displaynewHiddenvalue = $("#decimal").val();
alert(displaynewHiddenvalue);
});
});
</script>
</html>
note : to understand, first it shows the existing value, then in the button click , assign your new value , then display.(display with alsert, because then you can understand easily)
to assign the values in button click
var newhiddenVal = "new decimal";
$("#decimal").val(newhiddenVal);
do above in button click. hope this will help.
to get 10000 as the new value, in your button click
$("#clickme").click(function(){
var newhiddenVal = $("#number").val() +hiddenValue;
$("#decimal").val(newhiddenVal);
var displaynewHiddenvalue = $("#decimal").val();
alert(displaynewHiddenvalue);
});
i have code where you can add or delete textbox using .append() and .remove() in jquery, now i want to implode all the value of the textboxes separated by commas and pass it into another textbox located outside the script. how can i do it? here's the code for dymically adding and removing textbox. (not mine just got it here in stackoverflow)
HTML:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs /jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
</script>
Use .val() to set value of "another textbox" to values
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox").val(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<input id="anotherTextbox" type="text" />
I am new to building chrome extension. I am using content script to retrieve the values. But Iam unable to load the values into the popup.html.
Below is the code.
popup.html
<head>
<script src="popup.js"></script>
</head>
<body>
<form id="addbookmark">
<p><label for="title">Title</label><br />
<input type="text" id="title" name="title" size="50" value="" /></p>
<p><label for="url">Url</label><br />
<input type="text" id="url" name="url" size="50" value="" /></p
<p><label for="jsonName">Json Name</label><br />
<input type="text" id="jsonName" name="jsonName" value=""/></p>
<p><label for="jsonKey">Key</label><br />
<input type="text" id="jsonKey" name="jsonKey" value="" /></p>
<p><label for="jsonValue">JSON Value</label><br />
<input type="text" id="jsonValue" name="jsonValue" value="" /></p>
<p>
<input id="submitJson" type="submit" value="Send JSON Object / Valued" />
<!-- <span id="status-display"></span> -->
</p>
</form>
</body>
</html>
popup.js
function onPageDetailsReceived(pageDetails) {
document.getElementById('title').value = pageDetails.title;
document.getElementById('url').value = pageDetails.url;
document.getElementById('jsonValue').value = pageDetails.retrievedJsonValue;
}
window.addEventListener('load', function(evt) {
document.getElementById('submitJson').addEventListener('click',function(){
var jsonName = document.getElementById('jsonName').value;
if(jsonName.length > 1){
var jsonKey = document.getElementById('jsonKey').value;
var jsonValueToFind = "";
jsonValueToFind = jsonName+"."+jsonKey;
chrome.runtime.getBackgroundPage(function(eventPage) {
eventPage.getPageDetails(function(response){
alert(response.url);
document.getElementById('url').value = response.url;
}, jsonValueToFind);
});
}
});
});
event.js
function getPageDetails(callback,jsonValueToFind) {
chrome.tabs.executeScript(null,
{code:'var jsonValue ='+jsonValueToFind},
function(){
chrome.tabs.executeScript(null,{file: 'content.js' });
});
chrome.runtime.onMessage.addListener(function(message) {
callback(message);
});
}
content.js
chrome.runtime.sendMessage({
'title': document.title,
'url': window.location.href,
'retrievedJsonValue': jsonValue
});
Can anybody help me in storing the values to text boxes in the popup boxes, after the button click.
For the particular task the event page and separate content script file aren't even necessary:
manifest.json:
"permissions": ["tabs", "activeTab"]
popup.html:
...............
<script src="popup.js"></script>
</body>
</html>
popup.js ("load" event isn't needed since the script is executed after DOM is parsed):
document.getElementById('submitJson').addEventListener('click', function() {
var jsonName = document.getElementById('jsonName').value;
if(jsonName.length > 1) {
var jsonKey = document.getElementById('jsonKey').value;
getPageDetails(jsonName + "." + jsonKey, function(pageDetails) {
Object.keys(pageDetails).forEach(function(id) {
document.getElementById(id).value = pageDetails[id];
});
});
}
});
function getPageDetails(jsonValueToFind, callback) {
chrome.tabs.executeScript({code: jsonValueToFind}, function(result) {
var value = result[0];
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
callback({
url: tabs[0].url,
title: tabs[0].title,
jsonValue: value
});
});
});
}
tabId (the first parameter of executeScript) is simply omitted due to being optional.
injected script result is the last value in the code and it's passed in an array result.
I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
Please find my code below. My problem is that I the inner jQuery.get() doesn't get executed. Could some one help me out with this?
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert(url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
});
});
My html form looks like
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
I'd really appreciate any pointers.
Thanks!
The problem you are experiencing is that you dont do anything to stop your form from being submitted, thus it submits the form before it gets a chance to get the data from the worldweatheronline.com.
Change your click handler to be like this:
$(".button").click(function(event) {
event.preventDefault();
Here is my completed sample code that works the way you want it to:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function(event) {
event.preventDefault();
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert('first'+url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ){
return false;
}
});
}, 'jsonp');
});
});
</script>
</head>
<body>
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
</body>
</html>
Turn on Fiddler or Firebug and watch the HTTP call go out. You'll see the HTTP error message there. Also, turn on your console in Chrome or Firefox to see a potential JavaScript error.
Part of the problem could be the extra set of parentheses after your .get() function call. You have:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
It should be:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
});
}, 'jsonp');
Im going to go out on a limb and guess that (based on the url 'http://www.worldweatheronline.com/feed/weather.ashx?q=' ) that you are attempting to perform an AJAX request to an external site. This violates Same Domain Policy and will fail silently.