Hi I am trying to pass 3 values into some Javascript. This works for the first function. All values are found to be correct here......
function handleClick(cb,colum,id) {
if (cb.checked == true){
var checked = 1;
} else {
var checked = 0;
}
sendHddToPHP2(checked,column,id);
}
But once the second function is called I get nothing....
function sendHddToPHP2(editableObj,column,id) {
window.alert(editableObj);
$.ajax({
url: "update/hdd.php",
type: "POST",
data:'column='+column+'&editval='+editableObj+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
I added the alert to check if the variable was present and it didn't run. I can't see any typos and my knowledge isn't that great on Javascript. Is there something I have missed?
You have a typo: "colum" in the argument list.
Also, seems like you want to access the check box later in the Ajax callback, that will fail since you're trying to reference it via the "editableObj" value of the checkbox rather than the element.
As I understand you want your function to be like this:
function handleClick(cb,colum,id) {
var checked = (cb.checked)?1:0;//same as(cb.checked==true)1:0
sendHddToPHP2(checked,column,id);
}
but are you sure you want to return a 1 or 0? because in the second function you will be using $(1).css("background","#FDFDFD");
$(0).css("background","#FDFDFD");
Related
below is the information I need help with.
$(document).ready(function(){
$('.checkboxes :checkbox').click(function(){
if($(this).is(':checked')){
console.log(this.id + this.checked)
i want to set a variable with the samename of the id of the checked box
so if showItems was checked i would have a variable
var showItems = true;
I want this so I could see if showItems is checked which would alow me to perform the proper functions
i think i could do something like this
if($this.id = "withones"){
var withones = true;//on
}
if($this.id = "withoutOnes"){
var withoutOnes = true;//on
}
etc.
i feel like the above is a rookie way to code. lets say i have alot of checkboxes and it also looks like im repeating myself. I tried putting the ids in an array and loop through them but I got the html element in the console when i clicked on the box. I would like for someone to tell me if there is a more efficient way to set up these variables. and if so show me please.
Also I'm new to programming so thanks for your help so far. but I was also thinking about another problem. if I set up these variables here and I want to set up another function somewhere else to perform mathematical operations perse. i want that function to be able to evaluate the value of the withones and withoutOnes variables so I would like to do something like this in the function
function add(){
if(withones){ //true|| false
return 2 + 2;
}
if (withoutOnes) {
return 'blah'
};
}
I have had problems in the past trying to test the values that are set outside the function. I think i tried setting it in the arguments. but it just didn't read. If you could also show me an example of using the variables some where else in the code like discussed above that will be helpful . I forgot to mention that the value of the variable will change when the user clicks on the box. either to true or false. I think my problem in the past is that when the box is checked and then uncheck I had a problem changing the variable especially when it is being used in a separate function
}
});
});
You can have an object with your vars and add vars to that object dinamically:
var oVars = {}
// adding a var
oVars[nameVar] = valueVar
// accessing the var
oVars[nameVar]
You can capture the id with the attr() or you can just change the value of the checkbox with val() method in jQuery like this: FIDDLE
$(document).ready(function () {
$('.checkboxes').change(function (event) {
if ($(this).is(':checked')) {
var captureId = $(this).attr('id');
$(this).val(true);
alert($(this).val());
}
else {$(this).val(false);
alert($(this).val());}
});
});
Note that you can evaluate later all the checkboxes with one button and collect the value false or true from them. Why would you go through all of the complications with changing values of variables.
The other two answers are correct, though it sounds like you're wanting to know generally how to manage a big list of checkboxes with differing methods depending on type. It could look like this:
function multiply(this_object){
if((this_object.is(':checked')) && (this_object.attr("with") == 1))
return "with withone and checked";
else
return "is not both";
}
$(document).ready(function(){
$('.checkboxes').click(function(){
var this_object = $(this);
alert(multiply(this_object));
});
});
There should be no need to store all of the values in a variable unless you are passing all of them to another page - eg., via AJAX. Just reference them straight from the source field. If you need other info stored alongside, make a new attribute on the field - like the "with" one that I made for this example. See this Fiddle: http://jsfiddle.net/6ug6gL97/
your question is quite broad; so I’ll try to do my best to give you some kind of answer. First of all I’d use variables of global scope when declaring variables: withones and withoutOnes. Secondly, you wanted to avoid repetition in your code. Well, for that purpose I’d use JavaScript Arrays. In an array, you can add your variables as objects. In an object you can have your ids and other data “packed” neatly in the array, which in turn helps your code to become efficient.
Below is an array with objects:
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
The above array can be used in your $('.checkboxes :checkbox').click(function() handler and add() function to avoid repetition. The updated code is below where jQuery's each() method is used for looping Array elements.
The last a bit of your question was related to add() function. Well, this was the tricky bit of your question, and I tried to use a callback function hopefully in the right way to execute your functions from the array. In the add method I tried to follow this answer: https://stackoverflow.com/a/13343452/2048391
About the last bit I’m not 100% sure did I use a callback function in the right way; so I hope someone more familiar with these tricky JavaScript functions can correct me, if something needs to be changed –thanks.
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
$(document).ready(function () {
$('.checkboxes :checkbox').click(function () {
var id = this.id;
var checkedValue = this.checked;
$.each(objectArray, function (index, object) {
if (object.id === id) {
object.checked = checkedValue;
}
});
add();
});
function add() {
// clear results
$("#addResults").text("");
$.each(objectArray, function (index, object) {
if (object.checked === true) {
var returnValue = createCallback(object.method)
$("#addResults").append(returnValue + "<br>");
console.log(returnValue);
}
});
}
function createCallback(method) {
return method();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="withones"></input>
<label>With Ones</label>
<br>
<input type="checkbox" id="withoutOnes"></input>
<label>Without Ones</label>
</div>
<div id="addResults">
</div>
in arrayRec , onShow value should be a function.
Following is my reference code.
Any help?
This is my reference code:
if (rec.element_flag == '111'){
var arrayRec = [];
$.ajax({
type:'GET',
url: "/aps/one-url",
success: function(responseData){
for (var i = 0; i < responseData.length; i++){
var recJ;
var newFunction1 = function onshowdata(counter){
if(responseData[counter].fields.on_show_fn != null){
return function responseData[counter].fields.on_show_fn;
}
else
return;
}
recJ = {
element: responseData[i].fields.element_class,
placement: responseData[i].fields.placement,
title: responseData[i].fields.title,
content: responseData[i].fields.content,
onShow: newFunction1(i)
}
arrayRec.push(recJ);
console.log('-------arrayRec------');
console.log(arrayRec)
aps.walk.setupBootstrap(arrayRec);
}
},
error: function(){
alert('get failure');
}
});
}
Tried many ways but what I am missing?
in JSON, only text can be used, not objects. Functions are objects too. So, in JSON, name of the function can be passed, not the function object. An alternate way is to send the text of that entire function, which can be run using "eval", though this way is not recommended.
Use closure technique here. Define function above the ajax code, and use the name of the function inside it, which is a standard method of doing this.
I want to pass the "passedThisValue" to my "start_battle" function and use the "start_battle" function in my "Rematch". But the modal just hangs why is this happening? what could be wrong? Please help! :) Thank you.
CODE:
function start_battle(){
$.ajax({
data: {
receivePassedValue: passedThisValue
},
success: function(data){
}
});
}
$("#start_battle").click(function() {
$.ajax({
success: function(data){
var toAppend = '';
if(typeof data === "object"){
var passedThisValue = '';
for(var i=0;i<data.length;i++){
passedThisValue = data[i]['thisValue'];
}
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").dialog({
modal:true,
buttons: {
"Rematch": function(){
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").show(500);
});
When you call a function, you don't use function start_battle();, you just use start_battle();.
When you pass a value to a function, you need to use this syntax: start_battle(param1, param2);.
When you want to get a value from a function, you need to return it in the function, like so:
function start_battle(param1) {
// Do something
return param1;
}
When you want to store a returned value from a function, you do something like: var returned = start_battle(param1);
And the fact that you don't know why the modal just hangs, means that you didn't check the browser's error console, which can hold some pretty important information on what's wrong. Try checking that and posting here so we can see the current problem
Your function declaration seems a little off. I think you should leave off the $ from function. Just do this
function start_battle() {
Also, when you're calling a function, you don't say function before it. And if you want to pass a value to the function, you have to put it inside the parenthesis, both when defining the function and when calling it. Like this
function start_battle(someValue) {
// do some stuff with someValue
}
// inside your .click, call start_battle like this
start_battle(passedThisValue);
Pretty basic stuff. But either one of those problems could be causing the hang, which was likely a javascript error.
What I want to do is to read a body content of another html and save it as a var in a javascript function. What I currently have, using jQuery, is $(id of this document).load(link goes here). For example:
$("#test").load("/form.cgi?A1=?")
The form only has a body that contains <body>some value</body>
<a id="test">hello</a> This method works great because I don't have to use DOM at all.
However, I would like to store the data into a javascript variable. So, I think I have half of this done. Could someone shed some light on how to do so?
Ideally, something like:
'function(test)
{
var x = $.load(test);
//manipulate x such as parseInt/parseFloat, etc
}
'
Thanks!
You might want to change your approach to this:
var myVar = '';
$.get('/form.cgi?A1=?', function(data) {
myVar = data;
});
alert(myVar);
It is not possible to access the value of myVar outside the callback function because this Ajax call is asynchronous meaning while the page is being loaded, and the callback function has not been called and the value of myVar has not be changed, the alert statement executes which is why you get empty data.
To retain this answer, make use of the myVar inside the callback function like this:
var myVar = '';
var externalVar = '<p>text</p>';
$.get('/form.cgi?A1=?', function(data) {
myVar = data;
//use myVar here for whatever purpose you want it for
var myNewVar = myVar + ' ' + externalVar;
});
You can use the value of myVar as soon as the callback function is complete which could be 5sec, 30sec etc after the ajax call
<input type="button" value="pol" onclick="alert(myVar);" /> //should work
For further information see the links I posted in the comments
var x = $("#test").load("/form.cgi?A1=?").html();
This should do it if you want the content of the html file as it is.
.load() is short for $.ajax(), so, you can just use a normal Ajax request like so:
jQuery:
var result;
$.ajax({
type: 'POST',
url: '/form.cgi?A1=?',
success: function(data) {
result = data;
},
async: false
// async to false so that we don't access an empty variable before the request is finished
});
Demo: http://jsfiddle.net/SO_AMK/wHXrM/
Building on what codingbiz provided, this is what I currently have. It's not pretty, but it sure does the trick:
$.get( /form.cgi?A1=?, function(data){
document.getElementById("value").innerHTML = data;
var y = parseFloat(document.getElementById("value").innerHTML);
alert(y);
});
The reason why I used document.getElementById("value").innerHTML is to remove the <body> tag that surrounds the desired value (i.e <body>value</body>). This is the only way I know so far on how to parseInt/parseFloat properly. If I don't do this, then it return NaN due to the body tag. If you have a better way, do let me know. Thanks
I've got a nice little shopping basket where if the user deletes an item, the slideup jquery function is called and is disappears.
In the back ground, I'm removing it from the db with a call to a code igniter controller.
function delete_booking(id_booking, amount) {
if (user_total == null || user_total == '') {
var user_total = parseFloat(0);
}
$.ajax({
type: "POST",
data: '',
url: "/"+id_booking,
});
$("#booking_id_"+id_booking).slideUp();
var user_total = (parseFloat() - parseFloat() - parseFloat(user_total));
alert(user_total);
alert(parseFloat(user_total));
$('#booking_total').html(user_total);
}
What I can't fathom, is when I update the user total: $('#booking_total')
I need somehow to have the function remember the NEW total...
I've googled 'remembering JavaScript var' and similar, but I can't find exactly what I need...
My only other option is to do another call to the db with ajax to get the new total, but there MUST be a JS way to do this?
If you are not navigating to a different page, you can store the value in a variable that is outside the function (whether just on the page in the global namespace or the within the module in which the function resides).
var total;
function delete_booking(...)
{
...
total = user_total;
}
as you have said
I need somehow to have the function
remember the NEW total
a function cant remember a value, while a variable can, to solve your problem do one the below
1
var finalTotal;
function delete_booking(...)
{
//your more codes
$('#booking_total').html(user_total);
finalTotal = user_total;
}
now variable finalTotal hold the value
2
whenever you feel that you need to access the total read this way
var total=parseint($('#booking_total').html(),10) || 0;
But think method 1 is better than method 2
Because I "hate" a global approach for this type of problem, here is a little closure which will do the job of "remembering" the value (although I'm not really sure what exactly should be saved...^^)
var delete_booking = (function() {
var booking_total = $("#booking_total"),
total_amount = parseFloat(booking_total.html()) || 1000; // what ever the value should be...
return function(id, m) {
$.ajax(/* ... */);
$("#booking_id_"+id).slideUp();
total_amount -= m;
booking_total.html(total_amount);
}
}());