Jquery all my functions work except the following - javascript

(function($) {
var selectIds = new Array();
var sortOnSelect = false;
var nameModifier = "tsms";
function removeFormField() {
$(id).remove();
}
All the other functions after this work. This function says it undefined using firebug.
removeFormField is not defined
Another function creates this field and the top function is suppose to remove it.
<label for="txt4">Field 4 <input type="text" id="txt4" name="txt[]" size="20"> <a onclick="removeFormField("#row4"); return false;" href="#">Remove</a></label>

You need to put your function outside of the document ready function then call it from within.
(function($) {
var selectIds = new Array();
var sortOnSelect = false;
var nameModifier = "tsms";
removeFormField();
});
function removeFormField() {
$(id).remove();
}

In addition to the problem where the function is declared in the jQuery ready() handler, your function as written does not take an input value.
It should be:
function removeFormField(id) {
$(id).remove();
}

Related

Knockout multiple dynamic text boxes with one observable array

I am trying to save the data from the text-boxes to the localStorage using knockout JS! However I am new and not able to figure out this particular scenario. The field has same observable name! Please find my code below.
HTML Code:
<form data-bind="foreach: trialData">
<input type="text" name="name" data-bind="textInput: myData"><br>
</form>
JS Code:
var dataModel = {
myData: ko.observable('new'),
dataTemplate: function (myData) {
var self = this;
self.myData = ko.observable(myData);
}
};
dataModel.collectedNotes = function () {
var self = this;
self.trialData = ko.observableArray([]);
for (var i=0; i<5; i++) {
self.trialData.push (new dataModel.dataTemplate());
}
};
dataModel.collectedNotes();
ko.applyBindings(dataModel);
Traget: The data entered inside the text-boxes should be available in localStorage.
You need to define a Handler function to read the data from the Textboxes and save it to the localstorage. You need to reference the Data which is bound to the click event, which can be accessed using the first parameter. Knockout passes the data and event information as 2 arguments to the click handler function. So, you can add the event handler to your viewModel using the click binding and then unwrap the value and save it to localStorage.
saveToLocalStorage : function(data){
var datatoStore = JSON.stringify(data.trialData().map(x=>x.myData()));
console.log(datatoStore);
localStorage.setItem("TextBoxValue", datatoStore);
}
Complete Code: Please note since this is a sandboxed environment (Running this js Snippet on StackOverflow), localStorage wouldn't work, but it should work in your code. I have added a line in console to get the value to Store.
var dataModel = {
myData: ko.observable('new'),
dataTemplate: function (myData) {
var self = this;
self.myData = ko.observable(myData);
},
saveToLocalStorage : function(data){
var datatoStore = JSON.stringify(data.trialData().map(x=>x.myData()));
console.log(datatoStore);
localStorage.setItem("TextBoxValue", datatoStore);
}
};
dataModel.collectedNotes = function () {
var self = this;
self.trialData = ko.observableArray([]);
for (var i=0; i<5; i++) {
self.trialData.push (new dataModel.dataTemplate());
}
};
dataModel.collectedNotes();
ko.applyBindings(dataModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form data-bind="foreach: trialData">
<input type="text" name="name" data-bind="textInput: myData"><br>
</form>
<button data-bind="click:saveToLocalStorage">Save To local storage</button>

Unable to call JS function from onclick event

I am trying to call a JavaScript function from the onclick event of two different buttons. I have dug around and searched for like problems but have not found a solutions. When I click either button I get the error
Error: 'RemoveCode' is undefined'
What am I doing wrong?
<script type="text/javascript">
$(document).ready(function ()
{
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
});
</script>
Code for my buttons:
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select> <button class="removeButton" onclick="RemoveCode('Project')" type="button">-</button>
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select> <button class="removeButton" onclick="RemoveCode('Task')" type="button">-</button>
</li>
I should note that on the same page there are multiple change events for the other elements on the page and they all work fine. It is just this `onclickP that is failing.
Firstly note that in your if condition you need to use == (not =) to compare values.
To solve your issue you have two options. Firstly you could simply move the RemoveCode function out of the scope of the document.ready handler so that it can be accessed from the onclick attribute:
<script type="text/javascript">
function RemoveCode(codeType)
{
// your code...
}
$(document).ready(function ()
{
// your code...
});
</script>
Alternatively, it would be much better practice to add your event handlers using unobtrusive Javascript. As you're using jQuery, here's how you can do that:
$(function() {
$('button').click(function() {
var $selectedProjectsField = $("#SelectedProjects");
var $selectedProjectCodesField = $("#SelectedProjectCodes");
var $selectedTasksField = $("#SelectedTasks");
var $selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if ($(this).data('codetype') == "Project") {
selectedOption = $selectedProjectsField.find(':selected').index();
} else {
selectedOption = $selectedTasksField.find(':selected').index();
}
alert(selectedOption);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select>
<button class="removeButton" data-codetype="Project" type="button">-</button>
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select>
<button class="removeButton" data-codetype="Task" type="button">-</button>
</li>
</ul>
You are defining your RemoveCode method inside a closure. This function will thus not be available as onclick callbacks of your HTML elements.
You can just update your code to this and it should work:
<script type="text/javascript">
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
</script>
put your function out side of document.ready()
<script type="text/javascript">
$(document).ready(function () // No Need of this Function here
{ });
function RemoveCode(codeType) // Automatically load when Your page is getting loaded on Browser.
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
</script>
You are defining your ready() method inside of a closure.
You then have two approaches you can use. First is you can not use $(document).ready() as the buttons that call ready() can't be clicked until the document is ready anyway.
Second is you could bind the onclick inside of your $(document).ready().
$(document).ready(function() {
$('#firstItem').click(function() { Ready('Project'); });
....
});

GetElementById, am I pulling using the correct properties?

I don't think it's an onload issue anymore since I used the window.onload function. Here is the relevant pieces of the code. The console is saying the capitals is undefined. I thought I was defining it when I declared the value.
Thanks in advance!
<form name="shares">
<table>
<tr><td>Enter information here:</td></tr>
<tr>
<td>Capital to Invest</td>
<td id="capitalr"><input type="text" name="capital" onchange="calculate();"> </td>
</tr>
</form>
JS
window.onload = function() {
document.getElementById("hello").innerHTML="Hello";
var capitals = document.getElementById("capitalr");
var x = capitals.id;
var pps = document.shares.price.value;
};
function calculate () {
console.log("Hey");
console.log(capitals);
};
You are defining the variable within a function scope, which makes it inaccessible from outside that function scope. Define it outside and it will work:
var capitals;
window.onload = function() {
document.getElementById("hello").innerHTML="Hello";
capitals = document.getElementById("capitalr");
var x = capitals.id;
var pps = document.shares.price.value;
};
function calculate () {
console.log("Hey");
console.log(capitals);
};

Why the given code is not converting any text to uppercase?

<script>
var a = document.getElementById("text").value;
function toupper()
{
var mystring = new String(a);
document.write(a.toUpperCase());
}
</script>
**HTML**
<input type="text" id="text" name="text" />
<input type="button" id="clickme" value="clickme" name="click" onclick="toupper();"/>
Why the variable "a" cannot be accessed in the "toupper" function?
Pull var a inside the function & you don't have to write new String(a)
function toupper() {
var a = document.getElementById("text").value;
document.write(a.toUpperCase());
}
http://jsfiddle.net/Fn4Ns/3/
The execution of the statement var a = document.getElementById("text").value fails, because when it is executed, the element with id value of text has not been parsed, i.e. does not exist. You need to have document.getElementById("text") inside the function, or otherwise at a point where the element exists.
the problem is that you are trying to execute
var a = document.getElementById("text").value;
before the document finished loading.
please try the following it should work.
var a;
document.addEventListener('DOMContentLoaded', function() {
a = document.getElementById("text").value;
});
function toupper()
{
var mystring = new String(a);
document.write(a.toUpperCase());
}
Variable a is declared outside so it's accessible in both scopes callback for document ready and toupper function.
Get the element value, after you make sure the page (DOM) has been loaded
You need to re-retrieve the reference to the text field on every function call.
DEMO
var writeNewLine = function(text) {
var addChild = function(node) {
window.document.body.appendChild(node);
};
addChild(document.createElement('br'));
addChild(document.createTextNode(text.toUpperCase()));
};
window.toupper = function() {
var mystring = document.getElementById("text").value;
writeNewLine(mystring.toUpperCase());
}
This will work. you assigned value before text boxes has loaded
function toupper(){
var a = document.getElementById("text").value;
document.write(a.toUpperCase());
}

knockout binding print function text instead of variable value

I'm writing a small application in JS and I decided to use Knockout.
Everything work well except from a single value that is not printed correctly and I don't understand why.
This is the html view where error appends (viaggio.arrivo is not visualized, and in place of correct value appears a function code like this "function c(){if(0 <arguments.length){if ..." and so on)
<input data-bind="value: viaggio.arrivo" />
And this is the javascript View Model.
Code is pretty long so I put it in a jsFiddle.
function ViewModel() {
function Viaggiatore(nome, cognome, eta, citta) {
var self = this;
self.nome = nome; self.cognome = cognome;
self.eta = ko.observable(eta);
self.citta = ko.observable(citta);
}
function Viaggio(viaggiatore, partenza, arrivo, mete) {
var self = this;
self.viaggiatore = ko.computed(viaggiatore);
self.partenza = ko.computed(partenza);
self.arrivo = ko.observable(arrivo);
self.mete = ko.computed(mete);
}
self.viaggiatore = new Viaggiatore("Mario", "Rossi", 35, "Como");
self.viaggio = new Viaggio(
function(){ return self.viaggiatore.nome+" "+self.viaggiatore.cognome; },
function(){ return self.viaggiatore.citta; },
"Roma",
function(){ return "mete" ;}
);
}
ko.applyBindings(new ViewModel());
I think you need brackets on one of your parameters, like so:
<p data-bind="text: viaggio.partenza()"></p>
Check out the updated fiddle: http://jsfiddle.net/mGDwy/2/

Categories

Resources