JQuery set default is value is passed using url - php

This is a question is continuation of on my previous question on
JQuery next class
Thanks to all the guys who helped me with that issue.
Now I have problem in setting default values. There are 2 parts.
1st Part:
Say there is a link which loads default item1, item2 and also maybe item2
What I have done is the link pass values through URL like this
index.php?item1=3
Now how do i check this and enable respectively?
I have used PHP to check and set disabled in if nothing is passed, when passed it dosnt set disabled. but now the problem is 2nd item for which value has not been passed is disabled (item1 is enabled and set to default for the ids passed & item2, item3 are disabled) and to enable item2 I have reselect the item1.
Because, according to jquery item2 is unlocked only when item1 changes. How to override this?
2nd part: is similar to first but for certain pages item1 is set to default in code () and nothing is passed via url. Issue is same again.
I know both are of similar issues, just wondering if there is an easy solution rather than changing all part2 to part1 i.e passing item1 via url (I have to manually go into each page and change :( ).

Hey you need to check the value of Parameter by its name through This link. And Check whether value is null or not.and Do perform your operation on not null value.
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
This way you can call function to get value:
var Value = getParameterByName("Item1");

You can use a function to parse the querystring from jQuery.
QueryString (Taken from this SO answer)
(function($) {
$.qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Javascript
var item1 = $.qs('item1');
if (item1) {
// do something...
} else {
// set a default value...
}

Related

Conflicting jquery functions

I have built two functions which work separately (when the other is deleted) but do not work together. The overall aim is that when a person selects the number of results they want to see per page, this then reloads the page, and the value is put in the url and then retrieved using get in php; and then on the new page the selected value in the drop down menu to is the value what triggered the reload.
Jquery
$(document).ready(function(){
//the first section takes the value from the php script and then selects the option if it's not null - this works fine on it's own
var data = "<?php echo $rp;?>";
if (data){
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
//this too works fine on it's own but not with the above
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
Together, the first works fine, in that it re-selects the right value if, say, I put ?results=50 after sales.php but then the jQuery to trigger the reload doesn't work. What am I doing wrong?
Just to clarify. The first page is called "sales.php" and the drop down menu has the currently selected value of "10", with 25 and 50 being other options. When I click on another number the jquery doesn't work. However should I type into the url the ending "?result=50", for example, it does work; and the drop down menu now shows 50; when i click on ten, the url updates, and the drop down shows ten also; the problem then is they seem to conflict only at the start, as it were.
It would seem the problem may concern how jquery deals with php. Take for example the following first example which works, and then the second which doesn't:
1)
$(document).ready(function(){
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
2) This change function however will not trigger a reload of the page because of the inclusion of the php defined jquery variable.
$(document).ready(function(){
var data = "<?php echo $rp;?>";
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
This achieves what I want (I don't know if the php posed a problem or not). The function is from here - Get url parameter jquery Or How to Get Query String Values In js.
Also, I'm surprised nobody more experienced than me didn't point out what also seems to have made a difference; the "first" function in the original post needs to in fact be second.
So the below will reload a new page, when a user clicks on an option in a select menu with pre-defined options for how many results they want to see per page; this value will then show in the url, and, importantly, the current select value of the select menu will now be this value also; this is important so that if the user goes back to the original number of views, the change() function works still.
$(document).ready(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var data = getUrlParameter('results');
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
if (data)
{
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
});

Fixing jQuery plugin to handle duplicating nested fields with unique ID's

I have a quick question for you guys here. I was handed a set of lead generation pages and asked to get them up and running. The forms are great, expect for one small issue... they use the jQuery below to allow users to submit multiple instances of a data set by clicking an "Add another item" button. The problem is that the duplicated items are duplicated EXACTLY. Same name, id, etc. Obviously, this doesn't work when attempting to process the data via PHP, as only the first set is used.
I'm still learning jQuery, so I was hoping that someone could point me in the right direction for how to modify the plugin below to assign each duplicated field an incremental integer on the end of the ID and name assigned. So, the fields in each dataset are Role, Description, Age. Each additional dataset will use the ID & name syntax of fieldname#, where # represents numbers increasing by 1.
Thanks in advance for any advice!
/** https://github.com/ReallyGood/jQuery.duplicate */
$.duplicate = function(){
var body = $('body');
body.off('duplicate');
var templates = {};
var settings = {};
var init = function(){
$('[data-duplicate]').each(function(){
var name = $(this).data('duplicate');
var template = $('<div>').html( $(this).clone(true) ).html();
var options = {};
var min = +$(this).data('duplicate-min');
options.minimum = isNaN(min) ? 1 : min;
options.maximum = +$(this).data('duplicate-max') || Infinity;
options.parent = $(this).parent();
settings[name] = options;
templates[name] = template;
});
body.on('click.duplicate', '[data-duplicate-add]', add);
body.on('click.duplicate', '[data-duplicate-remove]', remove);
};
function add(){
var targetName = $(this).data('duplicate-add');
var selector = $('[data-duplicate=' + targetName + ']');
var target = $(selector).last();
if(!target.length) target = $(settings[targetName].parent);
var newElement = $(templates[targetName]).clone(true);
if($(selector).length >= settings[targetName].maximum) {
$(this).trigger('duplicate.error');
return;
}
target.after(newElement);
$(this).trigger('duplicate.add');
}
function remove(){
var targetName = $(this).data('duplicate-remove');
var selector = '[data-duplicate=' + targetName + ']';
var target = $(this).closest(selector);
if(!target.length) target = $(this).siblings(selector).eq(0);
if(!target.length) target = $(selector).last();
if($(selector).length <= settings[targetName].minimum) {
$(this).trigger('duplicate.error');
return;
}
target.remove();
$(this).trigger('duplicate.remove');
}
$(init);
};
$.duplicate();
Add [] to the end of the NAME attribute of the input field so for example:
<input type ="text" name="name[]"
This way your $POST['name'] will hold an array of strings. For that element. It will be an array with keys that are numbers from 0 to however many items it holds.

array of same id using getElementById error

i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}

Uncheck value for checkbox in jquery (with ajax and php)

I have an editable ajax table , and have a "unlock" field with a checkbox for every row.
When I check the chekbox I need to get the value 1 ( I'm ok for this part ! :)
My code to get the value of the cheked box:
( $("#unlock_input_" + ID).val(); ) )
But when I uncheck one of any checkbox , I need to get the value 0 ( I need help for this part)
So.... How can I do that in jquery ? Thx
You could throw on a :checked selector. Then you'll get back undefined when the box is unchecked, which is falsey, so:
var result = $("#unlock_input_" + ID + ":checked").val() || 0;
result will end up with the value of the checkbox if it's checked, or 0 if not, because of the way JavaScript's curiously-powerful || operator works.
Live example
Another way to write it:
var result = $("#unlock_input_" + ID).filter(":checked").val() || 0;
Or of course, the rather more direct:
var cb = $("#unlock_input_" + ID)[0],
result = cb.checked ? cb.value : 0;
change your code to this (using prop to ask for the checked-property):
var result = $("#unlock_input_" + ID).prop('checked')?1:0;
EDIT:
if you explicitly need the value instead of 1, just do:
var element = $("#unlock_input_" + ID);
var result = element.prop('checked')?element.val():0;
You can use the checked property of the checkbox to decide whether 1 or 0. Try this
if($("#unlock_input_" + ID)[0].checked){
alert("1");
}
else{
alert("0");
}
Alertnatively you can use jQuery is method to check whether the checkbox is checked or not.
if($("#unlock_input_" + ID).is(":checked")){
alert("1");
}
else{
alert("0");
}
You could check if it's chekced
if($("#unlock_input_" + ID).is(':checked')){
myVal = "1";
}
else{
myVal = "0";
}

jquery, checkboxes within nested div onclick show/hide submit

I have a page that has a series of div's in a shopping-cart system. Each is a product, when checking the checkbox, if there are options available and/or an acknowledge checkbox to be acknowledged before form submit, then keep the button hidden and show a div with another checkbox in it, when that checkbox if exists is checked then show button.
The show hide on each div is working properly (existing code), So I am trying to create a function to be called within that function for the onclick event.
where my issue arises is the check to see if another check box [shown in the example as(tmpId == "acknowledge")] does exist and that it is checked also before they can see the submit button, if not show the submit button. This would need to work for each product they click the first checkbox on [ie("id= "+feeSID+"_checkbox")]... $("#ocContainer") is the hidden container(with submit) to show if proper checkboxes are checked.. for each product selected.
the first part of each id is a variable generated by a sql query and passed to the function..
My Function:
var feeSID = "";
var feeVAL = "";
var pop = "";
function countChecked(feeSID) {
var n = $("input:checked").val();
var tmpId = $(this).attr("name");
if (tmpId == "acknowledge") {
console.log("acknowledge Clicked <br />");
} else {
feeVAL = $(this).attr("id");
}
if (feeVAL == '') {
return;
} else {
if ($("#" + feeSID + "_checkbox:checked")) {
console.log("id= " + feeSID + "_checkbox");
var pop = $("#" + feeSID + "_popup").length;
if (pop > 0) {
$(":checkbox").click(function () {
if (tmpId == "acknowledge") {
$("#ocContainer").show();
}
});
} else {
$("#ocContainer").show();
}
}
}
}
I hope my explanation was clear. I am getting an error of:
uncaught exception: Syntax error, unrecognized expression: #[object Object]_popup
I think that the exception is possibly caused by this line in your code:
var pop = $("#"+feeSID+"_popup").length;
At some point in your code, feeSID is assigned to an object. So, you are trying to use an object as part of your selector rather than a string. You need to make sure that feeSID is a string rather than an object before you try using it as part of the selector.
The error was caused by me trying to use an Obj as part of my selector. As Adam Prax had pointed out
var pop = $("#"+feeSID+"_popup").length;
At some point in my code, feeSID is assigned to an object. I solved it by redeclaring the Variable or Object as a string before accessing it again using new String(feeSID);
This solved the issue. I hope it helps someone else, all I could find on google pointed to the use of the syntax #name="name" which is no longer valid syntax in jQuery.

Categories