here this code just stores te options and atlast it produces the result from adio buttons. i want it inted of radio button use of textbox or input field. so what should be changed?
<script language="JavaScript">
var timer,timecounter=0
function readCookie(name)
{
var result=null;
var myCookie=document.cookie+";";
var searchName=name+"=";
var start=myCookie.indexOf(searchName);
var end;
if(start!=-1)
{
start+=searchName.length;
end=myCookie.indexOf(";",start);
result=myCookie.substring(start,end);
}
return result;
}
function writeCookie(name)
{
var expDate=new Date();
var day=1*24*60*60;
expDate.setTime(expDate.getTime()+day);
document.cookie=name+"="+timecounter;
}
function starttimer(counter,ans)
{
var cook
timecounter=parseInt(readCookie(<%=chr(34) & examname&"totaltime"& chr(34)%> ))
var index=-1
if(ans=="A")
index=0
else if(ans=="B")
index=1
else if(ans=="C")
index=2
else if(ans=="D")
index=3
if(document.examform.qno.value-1<=counter&&index!=-1)
document.examform.elements[index].checked=true
timer=setInterval("change()",1000)
}
function stoptimer()
{
writeCookie("<%=examname&"totaltime"%>");
clearInterval(timer)
}
function change()
{
var hrs,mins,secs;
hrs=parseInt(timecounter/3600);
mins=parseInt(timecounter/60);
secs=timecounter%60;
window.status="Time Remaining : "+hrs+":"+mins+":"+secs;
rem_time.innerText="Time Remaining :"+hrs+":"+mins+":"+secs;
timecounter--
if(timecounter==-1)
{
store_ans()
stoptimer()
document.examform.submit()
}
}
function store_ans()
{
var elems=document.examform.elements
var ans=""
for(var i=0;i<elems.length;i++)
if((elems[i].type=="radio"||elems[i].type=="checkbox")&&elems[i].checked)
ans=ans+elems[i].value
document.examform.answer.value=ans
if(ans=="")
document.examform.answer.value="Not Attempted"
stoptimer()
}
</script>
document.cookie: get and set the cookies associated with the current document (Mozilla Developer Network)
You can manipulate cookies with vanilla JavaScript using the document.cookie global.
To store multiple cookies, you have to assign document.cookie multiple times, e.g to store var a = '1'; var b = '2' you do
document.cookie = "a=1";
document.cookie = "b=2";
To read the cookie string, simply reference document.cookie, e.g console.log(document.cookie)
Also, your post has several editing and grammatical mistakes. Additionally, this is a question which can be easily answered with a Google search.
Related
I am trying to add a Mark all/Unmark all button in sub-list which is a type of inline-editor sub-list. below I have added a code for list type sub-list which will not work on inline-editor sub-list. Can anyone help to find this?
function button1Func(type) {
if (type=='edit' || 'view')
{
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var intCount = record.getLineItemCount('item');
var headrow = document.getElementById("item_headerrow");
var head = headrow.insertCell(0);
head.innerHTML ="Select";
for (var rep = 1; rep <= intCount; rep++)
{
var row = document.getElementById("item_row_"+rep);
var x = row.insertCell(0);
var newCheckbox = document.createElement("INPUT");
newCheckbox.setAttribute("type", "checkbox");
newCheckbox.setAttribute("id", "select_CheckBox"+rep);
x.appendChild(newCheckbox);
}
}
}
function button2Func(type) {
if (type=='edit' || 'view')
{
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var intCount = record.getLineItemCount('item');
for (var rep = 1; rep <= intCount; rep++)
{
var repId = record.getLineItemValue('item', 'item', rep);
if(document.getElementById("select_CheckBox"+rep).checked==true){
makecopyfun(repId);
}
else
{
continue;
}
}
alert("Success");
}
}
function makecopyfun(repId){
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var intCount = record.getLineItemCount('item');
record.insertLineItem('item',intCount + 1);
alert (intCount);
record.setCurrentLineItemValue('item','item',repId);
record.commitLineItem('item');
var id = nlapiSubmitRecord(record, true);
}
Not sure through the API because there's no record object, you could try using jQuery.
First write following code & create userEvent script and apply function name(initnoload) in beforeLoad Event.
Then Deploy that script on Quote.
function initonload(type, form, request) {
if (type=='edit' || type=='view') {
var list = form.getSubList("item");
list.addButton('custpage_markmark','Mark all','markall();'); //markall(); is function name from the client script
list.addButton('custpage_unmarkmark','Unmark all','unmarkall();'); //unmarkall(); is function name from client script
form.setScript('customscript_mark_all_item_quote'); // 'customscript_mark_all_item_quote' is the ID of script
}
}
Above code will add two buttons to Sublist and their action get executed in client script whose ScriptId we have Defined.
Now write the following code & create client script.(Note: Just save the client script, Don't specify any event function name and do not deploy it).
function markall() {
var count=nlapiGetLineItemCount('item'); //gets the count of lines
for(var i=1;i<=count;i++) {
nlapiSelectLineItem('item',i);
nlapiSetCurrentLineItemValue('item','custcol_checkbox_field','T',true,true); //'custcol_checkbox_field' is checkbox's field ID.
}
nlapiCommitLineItem('item');
}
function unmarkall() {
var count=nlapiGetLineItemCount('item');
for(var i=1;i<=count;i++) {
nlapiSelectLineItem('item',i);
nlapiSetCurrentLineItemValue('item','custcol_checkbox_field','F',true,true); //'custcol_checkbox_field' is checkbox's field ID.
}
nlapiCommitLineItem('item');
}
After saving the client script please paste it's ID in user event's form.setScript('Client script ID'). function
i hope this will help you out.
Please let me know if u face any difficulty.
Thank you.
I do came up with other idea as you can use the field which'll help you to mark/unmark all lines under sublist..you can add subtab to the form and under subtab you can add field and sublist. later you can apply script on that field which will help you to mark/unmark all sublist lines.
Here is the code...
form.addSubTab('custpage_tab', 'Main Tab');
form.addField('custpage_chkmark','checkbox','Mark/Unmark All',null,'custpage_tab');
form.addSubList('custpage_sublst','inlineeditor','SampleSubList','custpage_tab');
I have a problem with my Script. I want to do the following steps in this order:
1. Save the text in the input field.
2. Delete all text in the input field.
3. Reload the same text that was deleted before in the input field.
The problem with my script is that the ug()- function writes undefined in my textbox instead of the string that should be stored in var exput. The alert(exput) however shows me the correct content.
Help would be very much appreciated. And I'm sure there is better ways to do that, I'm quite new to this stuff.
HTML
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();deleter();ug()" />
Javascript
function merker() {
var merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
Your code is calling merker(); deleter(); ug(); in the onclick event, but ug() is already called by merker(). You should be doing this instead:
function merker() {
var merkzeug = document.getElementById('a').value;
deleter();
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
alert(exput);
document.getElementById('a').value = exput;
};
<textarea id="a" style="width: 320px; height: 200px;"></textarea>
<input type="checkbox" id="remember" onclick="merker();" />
I changed Your Javascript:
function merker() {
merkzeug = document.getElementById('a').value;//global variable without var
ug();//why You use it here? I think only for test. So delete it after.
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug() {
alert(merkzeug);
document.getElementById('a').value =merkzeug;
};
Problems with your code:
method ug was used with argument and without argument ( i changed to without )
to restore deleted value it must be saved to some variable, i saved to global merkzeug variable - this is not good practice but sufficient in this case
next i used merkzeug to restore value in textarea in ug() function
i do not know why You using ug() two times? maybe delete one of them is good thing to do.
In plunker - https://plnkr.co/edit/fc6iJBL80KcNSpaBd0s9?p=info
problem is: you pass undefined variable in the last ug function:
you do: merker(value) -> ug(value); delete(); ug(/*nothing*/);
or you set your merkzeung variable global or it will never be re-inserted in your imput:
var merkzeug = null;
function merker() {
merkzeug = document.getElementById('a').value;
ug(merkzeug);
};
function deleter() {
if(document.getElementById('remember').checked == true)
{
document.getElementById('a').value = "";
}
else {document.getElementById('a').value = "";
}
};
function ug(exput) {
if (typeof exput === 'undefined') exput = merkzeung;
alert(exput);
document.getElementById('a').value = exput;
};
I have the following code...
var leave_page_confirm=false;
if ($(':input.common_class').val().length !== 0) {
var leave_page_confirm=true;
}
window.onbeforeunload = save_data_check;
function save_data_check()
{
if (leave_page_confirm) {
return "You have unsaved information on the page.";
}
}
I'm trying to see if any inputs on the page have value. If they don't then you can leave the page without a message. If they do, then there is a message you asking if you would like to leave the page. All of the inputs on my page have a common class.
Some information about the logic I have followed:
This code doesn't save anything, if you need to store some information just with JS, so on the client computer and this will depend on the cache, you can use the cookie(the information are temporary since rely on cookies that can be deleted, so maybe you can store the unsaved values to wait the user to submit them).
The first snippet is based on the idea that the inputs will not be cleared once you save the information(they will keep the information), this means that js checks if the user makes any change to them (can be smarter, maybe check if the value is really different from the beginning one) and set var to true/false, once the user leaves the page then var is checked.
The second script is based on the idea that the inputs are part of a form or something like this, so once it get submitted the inputs will be cleared.
if the user leaves the page the code check if the are any non-empty (saved or not) value.
To sum up:
the first checks if any change has been made to the input
the second one check if the input contains a value
I don't understand the unsaved data: unsaved data or empty values? I mean if a user save a non empty value and then clean the input?
This is what I thought: basically every time the input change it sets the saved var to false and once you hit the button save (or every other logic) it sets the value to true, otherwise once you unload the page the script check the var to see if it is true or false
HTML:
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<input type='input' class='test' />
<button class='save'>Save</button>
JQUERY
var saved= true;
window.onbeforeunload = function () {
if (!saved) {
return 'Would you like to save?';
}
};
$('.test').on('input', function(){
saved=false;
});
$('.save').click(function(){
saved=true;
});
If you just need to check for the input value:
window.onbeforeunload = function () {
var saved= true;
$('.test').val(function(e,v){
//This check if the value is not empty
//if you want any kind of value use if(v)
if(v.trim()!=""){
saved=false;
return;
}
});
if(!saved)
return 'Would you like to save?';
};
You can achive this even with pure js:
window.onbeforeunload = function () {
var saved= true,
items= document.getElementsByClassName('test'),
count= items.length;
for(i=0;i<count;i++){
if(items[i].value!=""){ //if(items[i].value)
saved=false;
break;
}
};
if(!saved)
return 'Would you like to save?';
};
EDIT COOKIE PART - FIXED - WORKS
$(document).ready(function() {
var cookieVal = getCookie('formValue');
if(cookieVal){
var list=$.parseJSON(cookieVal);
$('.test').each(function(){
if($(this).attr('name') in list)
$(this).val(list[$(this).attr('name')]);
});
document.cookie = 'formValue=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
});
window.onbeforeunload = function () {
var saved= true;
$('.test').each(function(){
if($(this).val().trim()!=""){
saved=false;
return;
}
});
if(!saved){
var itemObj= new Object,
d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000));
var expires = "expires="+d.toUTCString();
$('.test').val(function(e,v){
if($(this).attr('name'))
itemObj[$(this).attr('name')]=v;
});
itemObj=JSON.stringify(itemObj);
document.cookie = 'formValue=' + itemObj + "; " + expires;
return 'Would you like to save?';
}
};
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Since you are using jQuery already use each.
var leave_page_confirm = true;
$('.common_class').each(function(){
if($(this).val().length == 0)
leave_page_confirm = false
});
Also check for false if any of them are false it will always return false instead of worrying about checking every one and setting true or false. It will always be false for 1 empty.
One crude way
var leave_page_confirm=false;
$('input').each(
function(){
if($(this).val()){
leave_page_confirm = true;
}
});
try this
var changesSaved =true;
function hasPendingChanges()
{
changesSaved=$(':input.common_class').val().length == 0;
}
window.onbeforeunload = save_data_check;
function save_data_check()
{
if (!changesSaved) {
return "You have unsaved information on the page.";
}
}
I generally use change event to track any of the input has changes as,
var leave_page_confirm = false;
$(function() {
$(':input.common_class').change(function(){
leave_page_confirm = true;
if(!leave_page_confirm)
window.onbeforeunload = save_data_check;
});
});
function save_data_check(){
return "You have unsaved information on the page.";
}
I have some Javascript that adds some disclaimer text and a confirmation CheckBox, just before a submit button on a PHP/WordPress page. What I'd like to happen is the script checks for the existence of a cookie. If cookie doesn't exist (or has expired), then to add the disclaimer text, the checkbox and force the user to click the Checkbox before proceeding. But once done, a cookie is written so that the next time the script runs, if bypasses the disclaimer text, checkbox and just allows the user to hit 'submit'.
So, something like:
if cookie-exists {
// straight to submit part of the code
} else {
// show disclaimer and checkbox
// Only allow user to hit submit if checkbox is ticked
// Set the cookie with an expire of a day
}
I can see an answer on setting / reading a cookie here > How do I create and read a value from cookie?
But I'm just struggling to get it into the code snippet below.
Any pointers or help would be greatly appreciated. Thanks.
Code snippet follows:
function add_listing_select_cb()
{
?>
<script type="text/javascript">
jQuery(document).ready(function ($){
var checkbox_cont = '<br><input type="checkbox" name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}
Have you tried something similar to this?
function add_listing_select_cb()
{
?>
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
jQuery(document).ready(function ($){
if (getCookie("anything")!==true){
var checkbox_cont = '<br><input type="checkbox" **required** name="I_Agree" id="I_Agree" value="I_Agree" /> <b>Disclaimer text here....</b>';
jQuery(".property-search input[type='submit']").before(checkbox_cont);
jQuery("#searchform").submit(function () {
if (!jQuery("#I_Agree").is(":checked")) {
alert("Please first agree with the terms.");
return false;
};
});
}
var $sel = $('#showresultsbasedonourratings'),
$opts = $sel.children();
$optsSorted = [];
$optsSorted.push($opts.eq(0));
for (var i = $opts.length - 1; i > 0; i--) {
$optsSorted.push($opts.eq(i));
};
console.log($optsSorted);
$sel.empty();
$sel.append($optsSorted);
});
</script>
<?php
}
Users select checkboxes and hit select, the results are displayed, but then checkboxes lose their checked state and that will make users confused what they checked. I am trying to presist the checkboxes state after the page refresh. I am not able to acheive this yet, but I am hopeful its doable. Can someone help me in the right direction?
Emergency Centers<input name="LocType" type="checkbox" value="Emergency"/>
Out-Patient Centers<input name="LocType" type="checkbox" value="Out-Patient"/>
Facilities<input name="LocType" type="checkbox" value="Facility"/>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit"><span>Search</span></a></div>
$(document).ready(function() {
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('a.searchButton').click(function(){
var checkboxValues = $("input[name=LocType]:checked").map(function() {
return "\"" + $(this).val() + "\"";}).get().join(" OR ");
//Now use url variable which has all the checked LocType checkboxes values and jump to url
window.location = url+'&k='+checkboxValues;
});
//Keep the selected checked on page redirect
var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
}
});
not sure if you're still interested in this, but I had the same problem a little while ago, and found this generic piece of JS that persist checkbox states:
// This function reads the cookie and checks/unchecks all elements
// that have been stored inside. It will NOT mess with checkboxes
// whose state has not yet been recorded at all.
function restorePersistedCheckBoxes() {
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
var el = document.getElementById(aPair[0]);
if(el) {
el.checked = aPair[1] == '1';
}
}
}
// This function takes as input an input type="checkbox" element and
// stores its check state in the persistence cookie. It is smart
// enough to add or replace the state as appropriate, and not affect
// the stored state of other checkboxes.
function persistCheckBox(el) {
var found = false;
var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
if(aPair[0] == el.id) {
// State for this checkbox was already present; replace it
aStatus[i] = currentStateFragment;
found = true;
break;
}
}
if(!found) {
// State for this checkbox wasn't present; add it
aStatus.push(currentStateFragment);
}
// Now that the array has our info stored, persist it
setPersistedCheckStatus(aStatus);
}
// This function simply returns the checkbox persistence status as
// an array of strings. "Hides" the fact that the data is stored
// in a cookie.
function getPersistedCheckStatus() {
var stored = getPersistenceCookie();
return stored.split(',');
}
// This function stores an array of strings that represents the
// checkbox persistence status. "Hides" the fact that the data is stored
// in a cookie.
function setPersistedCheckStatus(aStatus) {
setPersistenceCookie(aStatus.join(','));
}
// Retrieve the value of the persistence cookie.
function getPersistenceCookie()
{
// cookies are separated by semicolons
var aCookie = document.cookie.split('; ');
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split('=');
if ('JS_PERSISTENCE_COOKIE' == aCrumb[0])
return unescape(aCrumb[1]);
}
return ''; // cookie does not exist
}
// Sets the value of the persistence cookie.
// Does not affect other cookies that may be present.
function setPersistenceCookie(sValue) {
document.cookie = 'JS_PERSISTENCE_COOKIE=' + escape(sValue);
}
// Removes the persistence cookie.
function clearPersistenceCookie() {
document.cookie = 'JS_PERSISTENCE_COOKIE=' +
';expires=Fri, 31 Dec 1999 23:59:59 GMT;';
}
Just make sure your checkboxes have an onChange= persistCheckBox(this); attached to them
eg.
<label for= "LocType">User Preference</label>
<input name= "LocType" type= "checkbox" onChange= persistCheckBox(this);"/>
And also an onLoad in your opening body tag:
<body onload="restorePersistedCheckBoxes();">
I would be more inclined to go with HTML5 web storage (faster and more secure) but cookies would also do the job. Here is a link to some samples using HTML5 http://www.w3schools.com/html5/html5_webstorage.asp