jQuery - google chrome won't get updated textarea value - google-chrome

I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.

I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>

Related

How change display value/color td based on JSON

I'm working on an app where I get a json via an ajax call. This json contains objects where you get a certain status code per extension (1 = online, 2, is ringing, 3 = busy)
How can I ensure that the value that I get back is converted to the text (preferably with a different color of the )
So when I get a 1 back I want it to show Online, and with a 2 Ring etc
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
// console.log(JSON.parse(data.responseText));
// console.log(JSON.parse(data.responseJSON));
console.log(data['entry']);
var event_data = '';
$.each(data.entry, function(index, value){
/* console.log(data['entry']);*/
event_data += '<tr>';
event_data += '<td>'+value.extension+'</td>';
event_data += '<td>'+value.status+'</td>';
<!--event_data += '<td>'+value.registration+'</td>';-->
event_data += '</tr>';
});
$("#list_table_json").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
Thanks in advance!
I have change the code
function get_blf() {
$.ajax({
type:'GET',
url: url,
dataType: 'json',
error: function(jqXHR, exception) {ajax_error_handler(jqXHR, exception);},
success: function(data){
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.status;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
}
});
}
}
and add the css, but now i can't get any values back. but now i can't get any values back. (sorry I'm fairly new to javascript)
Please use the DOM API
One way of getting colors would be to use CSS classes for the status:
// js
...
$.each(data.entry, (index, value) => {
const tableRow = document.createElement('tr');
const tdExtension = document.createElement('td');
extension.textContent = value.extension;
const tdStatus = document.createElement('td');
if (value.status == 3) status.textContent = 'Busy';
if (value.status == 2) status.textContent = 'Ringing';
if (value.status == 1) status.textContent = 'Online';
tdStatus.classList.add(`status-${value.status}`);
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
...
// css
.status-1 {
color: green;
}
.status-2 {
color: red;
}
.status-3 {
color: orange;
}
I finally got the script working. I am now trying to build in a polling, however I see that the ajax call is executed again and the array is fetched. However, the table is not refreshed but a new table is added, does anyone know a solution for this?
code I'm using now for the repoll is
function repoll(poll_request, poll_interval, param=null) {
if (poll_interval != 0) {
if (window.timeoutPool) {
window.timeoutPool.push(setTimeout(function() { poll_request(param); }, poll_interval));
}
else {
setTimeout(function() { poll_request(param); }, poll_interval);
}
}
else {
log_msg('Poll cancelled.');
}
}
tableRow.appendChild(tdExtension);
tableRow.appendChild(tdNr);
tableRow.appendChild(tdStatus);
$('#list_table_json').append(tableRow);
});
repoll(get_blf, poll_interval_blf);

Which method is best to pass data from view to controller codeigniter?

I am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});

Codeception acceptance test error for save/reset

I am trying to perform acceptance tests for my website using Codeception, and I am experiencing a strange error due to a reset button on the form I am testing. Basically, my test for clicking on 'Save' works only if either the reset button on my form is AFTER the Save button, or if the reset button is left off the form altogether. If the reset button is inserted in the form before the save button, Codeception throws an Unreachable field "reset" error. Here is my Codeception code:
<?php
$I = new WebGuy($scenario);
$I->wantTo('find an employee in the database');
$I->amOnPage('/employees/find/');
$I->fillField('employeeLookup[first_name]', 'Sergi');
$I->click('Save', '#employeeLookup_save');
$I->see('Based on your search for Sergi, the following employees were found:');
$I->see('Remmele');
$I->see('Feb 28 1992');
And here is my HTML (much of it being generated from Symfony2):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Find existing employee</title>
</head>
<body>
<div id="content">
<p>Hello, enter either the first name, or the last name of the employee
you are searching for.</p>
<form name="employeeLookup" method="post" action="">
<div><label for="employeeLookup_first_name" class="required">Name: </label><input type="text" id="employeeLookup_first_name" name="employeeLookup[first_name]" required="required" /></div>
<div><button type="reset" id="employeeLookup_reset" name="employeeLookup[reset]">Reset</button></div>
<div><button type="submit" id="employeeLookup_save" name="employeeLookup[save]">Save</button></div>
<input type="hidden" id="employeeLookup__token" name="employeeLookup[_token]" value="RcpMVTGgB6WhKgDoXXRwmV_l4AFYKWTZko-dnBDhhvM" /></form>
</div>
<div id="sfwdte5d291" class="sf-toolbar" style="display: none"></div><script>/*<![CDATA[*/ Sfjs = (function() { "use strict"; var noop = function() {}, profilerStorageKey = 'sf2/profiler/', request = function(url, onSuccess, onError, payload, options) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); options = options || {}; xhr.open(options.method || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 === xhr.readyState && 200 === xhr.status) { (onSuccess || noop)(xhr); } else if (4 === xhr.readyState && xhr.status != 200) { (onError || noop)(xhr); } }; xhr.send(payload || ''); }, hasClass = function(el, klass) { return el.className.match(new RegExp('\\b' + klass + '\\b')); }, removeClass = function(el, klass) { el.className = el.className.replace(new RegExp('\\b' + klass + '\\b'), ' '); }, addClass = function(el, klass) { if (!hasClass(el, klass)) { el.className += " " + klass; } }, getPreference = function(name) { if (!window.localStorage) { return null; } return localStorage.getItem(profilerStorageKey + name); }, setPreference = function(name, value) { if (!window.localStorage) { return null; } localStorage.setItem(profilerStorageKey + name, value); }; return { hasClass: hasClass, removeClass: removeClass, addClass: addClass, getPreference: getPreference, setPreference: setPreference, request: request, load: function(selector, url, onSuccess, onError, options) { var el = document.getElementById(selector); if (el && el.getAttribute('data-sfurl') !== url) { request( url, function(xhr) { el.innerHTML = xhr.responseText; el.setAttribute('data-sfurl', url); removeClass(el, 'loading'); (onSuccess || noop)(xhr, el); }, function(xhr) { (onError || noop)(xhr, el); }, options ); } return this; }, toggle: function(selector, elOn, elOff) { var i, style, tmp = elOn.style.display, el = document.getElementById(selector); elOn.style.display = elOff.style.display; elOff.style.display = tmp; if (el) { el.style.display = 'none' === tmp ? 'none' : 'block'; } return this; } } })();/*]]>*/</script><script>/*<![CDATA[*/ (function () { Sfjs.load( 'sfwdte5d291', '/employees/app_dev.php/_wdt/e5d291', function(xhr, el) { el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none'; if (el.style.display == 'none') { return; } if (Sfjs.getPreference('toolbar/displayState') == 'none') { document.getElementById('sfToolbarMainContent-e5d291').style.display = 'none'; document.getElementById('sfToolbarClearer-e5d291').style.display = 'none'; document.getElementById('sfMiniToolbar-e5d291').style.display = 'block'; } else { document.getElementById('sfToolbarMainContent-e5d291').style.display = 'block'; document.getElementById('sfToolbarClearer-e5d291').style.display = 'block'; document.getElementById('sfMiniToolbar-e5d291').style.display = 'none'; } }, function(xhr) { if (xhr.status !== 0) { confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\n\nDo you want to open the profiler?') && (window.location = '/employees/app_dev.php/_profiler/e5d291'); } } ); })();/*]]>*/</script>
</body>
</html>
Finally, here is the relevant output of the error message from Codeception:
1) Failed to find an employee in the database in FindEmployeeCept.php
Sorry, I couldn't click "Save","#employeeLookup_save":
Behat\Mink\Exception\ElementException: Exception thrown by ((//html/descendant-or-self::*[#id = 'employeeLookup_save'])[1]/.//input[./#type = 'submit' or ./#type = 'image' or ./#type = 'button'][(((./#id = 'Save' or ./#name = 'Save') or contains(./#value, 'Save')) or contains(./#title, 'Save'))] | .//input[./#type = 'image'][contains(./#alt, 'Save')] | .//button[((((./#id = 'Save' or ./#name = 'Save') or contains(./#value, 'Save')) or contains(normalize-space(string(.)), 'Save')) or contains(./#title, 'Save'))] | .//input[./#type = 'image'][contains(./#alt, 'Save')] | .//*[./#role = 'button'][(((./#id = 'Save' or ./#name = 'Save') or contains(./#value, 'Save')) or contains(./#title, 'Save') or contains(normalize-space(string(.)), 'Save'))])[1]
Unreachable field "reset"
Again, if the reset button is rendered after the save button in the HTML, the acceptance tests pass just fine. Also, if the reset button is left off of the form entirely, the acceptance test passes as well. Does anyone have any idea what is causing this?

Polyfill HTML5 form attribute (for input fields)

This is the markup I use:
<input type="text" form="myform" name="inp1" />
<form id="myform" name="myform">
...
</form>
Now I realized that it does not work for old IE and therefore I am searching for a HTML 5 polyfill.
Anyone aware of a certain polyfill which covers this HTML5 feature?
I wrote this polyfill to emulate such feature by duplicating fields upon form submission, tested in IE6 and it worked fine.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var sampleElement = $('[form]').get(0);
var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
if (sampleElement && window.HTMLFormElement && (sampleElement.form instanceof HTMLFormElement || sampleElement instanceof window.HTMLFormElement) && !isIE11) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
The polyfill above doesn't take into account the Edge browser. I have amended it to use feature detection, which I have tested in IE7+, Edge, Firefox (mobile/desktop), Chrome (mobile/desktop), Safari (mobile/desktop), and Android browser 4.0.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
I improved patstuart's polyfill, such that:
a form can now be submitted several times, e.g. when using the target attribute (external fields were duplicated previously)
reset buttons now work properly
Here it is:
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
var CLASS_NAME_POLYFILL_MARKER = "html-5-polyfill-form-attr-marker";
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.attr('class', CLASS_NAME_POLYFILL_MARKER)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e, origSubmit) {
// clean up form from last submit
$('.'+CLASS_NAME_POLYFILL_MARKER, this).remove();
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// add data from external submit, if needed:
if (origSubmit && origSubmit.name)
data.push({name: origSubmit.name, value: origSubmit.value})
// append data to form
$(this).appendField(data);
})
//submit and reset behaviour
$('button[type=reset], input[type=reset]').click(function() {
//extend reset buttons to fields with matching form attribute
// reset form
var formId = $(this).attr("form");
var formJq = $('#'+formId);
if (formJq.length)
formJq[0].reset();
// for elements outside form
if (!formId)
formId = $(this).closest("form").attr("id");
$fields = $('[form=' + formId + ']');
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
});
$('button[type=submit], input[type=submit], input[type=image]').click(function() {
var formId = $(this).attr("form") || $(this).closest("form").attr("id");
$('#'+formId).trigger('submit', this); //send clicked submit as extra parameter
});
})(jQuery);
after reading thru the docs of webshim it seems it has a polyfill for that.
http://afarkas.github.io/webshim/demos/demos/webforms.html
I made a vanilla JavaScript polyfill based on the above polyfills and uploaded it on GitHub: https://github.com/Ununnilium/form-attribute-polyfill.
I also added a custom event to handle the case when submit is processed by JavaScript and not directly by the browser. I tested the code only shortly with IE 11, so please check it yourself before use. The polling should maybe be replaced by a more efficient detection function.
function browserNeedsPolyfill() {
var TEST_FORM_NAME = "form-attribute-polyfill-test";
var testForm = document.createElement("form");
testForm.setAttribute("id", TEST_FORM_NAME);
testForm.setAttribute("type", "hidden");
var testInput = document.createElement("input");
testInput.setAttribute("type", "hidden");
testInput.setAttribute("form", TEST_FORM_NAME);
testForm.appendChild(testInput);
document.body.appendChild(testInput);
document.body.appendChild(testForm);
var sampleElementFound = testForm.elements.length === 1;
document.body.removeChild(testInput);
document.body.removeChild(testForm);
return !sampleElementFound;
}
// Ideas from jQuery form attribute polyfill https://stackoverflow.com/a/26696165/2372674
function executeFormPolyfill() {
function appendDataToForm(data, form) {
Object.keys(data).forEach(function(name) {
var inputElem = document.createElement("input");
inputElem.setAttribute("type", "hidden");
inputElem.setAttribute("name", name);
inputElem.value = data[name];
form.appendChild(inputElem);
});
}
var forms = document.body.querySelectorAll("form[id]");
Array.prototype.forEach.call(forms, function (form) {
var fields = document.querySelectorAll('[form="' + form.id + '"]');
var dataFields = [];
Array.prototype.forEach.call(fields, function (field) {
if (field.disabled === false && field.hasAttribute("name")) {
dataFields.push(field);
}
});
Array.prototype.forEach.call(fields, function (field) {
if (field.type === "reset") {
field.addEventListener("click", function () {
form.reset();
Array.prototype.forEach.call(dataFields, function (dataField) {
if (dataField.nodeName === "SELECT") {
Array.prototype.forEach.call(dataField.querySelectorAll('option'), function (option) {
option.selected = option.defaultSelected;
});
} else {
dataField.value = dataField.defaultValue;
dataField.checked = dataField.defaultChecked;
}
});
});
} else if (field.type === "submit" || field.type === "image") {
field.addEventListener("click", function () {
var obj = {};
obj[field.name] = field.value;
appendDataToForm(obj, form);
form.dispatchEvent(eventToDispatch);
});
}
});
form.addEventListener("submit", function () {
var data = {};
Array.prototype.forEach.call(dataFields, function (dataField) {
data[dataField.name] = dataField.value;
});
appendDataToForm(data, form);
});
});
}
// Poll for new forms and execute polyfill for them
function detectedNewForms() {
var ALREADY_DETECTED_CLASS = 'form-already-detected';
var newForms = document.querySelectorAll('form:not([class="' + ALREADY_DETECTED_CLASS + '"])');
if (newForms.length !== 0) {
Array.prototype.forEach.call(newForms, function (form) {
form.className += ALREADY_DETECTED_CLASS;
});
executeFormPolyfill();
}
setTimeout(detectedNewForms, 100);
}
// Source: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
function polyfillCustomEvent() {
if (typeof window.CustomEvent === "function") {
return false;
}
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: undefined};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}
if (browserNeedsPolyfill()) {
polyfillCustomEvent(); // IE is missing CustomEvent
// This workaround is needed if submit is handled by JavaScript instead the browser itself
// Source: https://stackoverflow.com/a/35155789/2372674
var eventToDispatch = new CustomEvent("submit", {"bubbles": true, "cancelable": true});
detectedNewForms(); // Poll for new forms and execute form attribute polyfill for new forms
}
I take some time to send an update for this polyfill because it doesn't work with MS Edge.
I add 2 line to fix it :
var isEdge = navigator.userAgent.indexOf("Edge");
if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11 && isEdge == -1) {
// browser supports it, no need to fix
return;
}
UPDATE: Edge now support it:
https://caniuse.com/#feat=form-attribute

jquery cookies for different countries link

I am trying to do cookie stuff in jquery
but it not getting implemented can you guys fix my problem
html code
<a rel="en_CA" class="selectorCountries marginUnitedStates locale-link" href="http://www.teslamotors.com/en_CA">united states</a>
<a rel="en_US" class="selectorCountries marginSecondCountry locale-link" href="http://www.teslamotors.com/en_CA">canada</a>
<a rel="en_BE" class="selectorCountries marginCanadaFrench locale-link" href="http://www.teslamotors.com/en_BE">canada(french)</a>
i am providing my js code below
http://jsfiddle.net/SSMX4/76/
when i click the different country links in the pop up it should act similar to this site
http://www.teslamotors.com/it_CH
$('.locale-link').click(function(){
var desired_locale = $(this).attr('rel');
createCookie('desired-locale',desired_locale,360);
createCookie('buy_flow_locale',desired_locale,360);
closeSelector('disappear');
})
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
function checkCookie(){
var cookie_locale = readCookie('desired-locale');
var show_blip_count = readCookie('show_blip_count');
var tesla_locale = 'en_US'; //default to US
var path = window.location.pathname;
// debug.log("path = " + path);
var parsed_url = parseURL(window.location.href);
var path_array = parsed_url.segments;
var path_length = path_array.length
var locale_path_index = -1;
var locale_in_path = false;
var locales = ['en_AT', 'en_AU', 'en_BE', 'en_CA',
'en_CH', 'de_DE', 'en_DK', 'en_GB',
'en_HK', 'en_EU', 'jp', 'nl_NL',
'en_US', 'it_IT', 'fr_FR', 'no_NO']
// see if we are on a locale path
$.each(locales, function(index, value){
locale_path_index = $.inArray(value, path_array);
if (locale_path_index != -1) {
tesla_locale = value == 'jp' ? 'ja_JP':value;
locale_in_path = true;
}
});
// debug.log('tesla_locale = ' + tesla_locale);
cookie_locale = (cookie_locale == null || cookie_locale == 'null') ? false:cookie_locale;
// Only do the js redirect on the static homepage.
if ((path_length == 1) && (locale_in_path || path == '/')) {
debug.log("path in redirect section = " + path);
if (cookie_locale && (cookie_locale != tesla_locale)) {
// debug.log('Redirecting to cookie_locale...');
var path_base = '';
switch (cookie_locale){
case 'en_US':
path_base = path_length > 1 ? path_base:'/';
break;
case 'ja_JP':
path_base = '/jp'
break;
default:
path_base = '/' + cookie_locale;
}
path_array = locale_in_path != -1 ? path_array.slice(locale_in_path):path_array;
path_array.unshift(path_base);
window.location.href = path_array.join('/');
}
}
// only do the ajax call if we don't have a cookie
if (!cookie_locale) {
// debug.log('doing the cookie check for locale...')
cookie_locale = 'null';
var get_data = {cookie:cookie_locale, page:path, t_locale:tesla_locale};
var query_country_string = parsed_url.query != '' ? parsed_url.query.split('='):false;
var query_country = query_country_string ? (query_country_string.slice(0,1) == '?country' ? query_country_string.slice(-1):false):false;
if (query_country) {
get_data.query_country = query_country;
}
$.ajax({
url:'/check_locale',
data:get_data,
cache: false,
dataType: "json",
success: function(data){
var ip_locale = data.locale;
var market = data.market;
var new_locale_link = $('#locale_pop #locale_link');
if (data.show_blip && show_blip_count < 3) {
setTimeout(function(){
$('#locale_msg').text(data.locale_msg);
$('#locale_welcome').text(data.locale_welcome);
new_locale_link[0].href = data.new_path;
new_locale_link.text(data.locale_link);
new_locale_link.attr('rel', data.locale);
if (!new_locale_link.hasClass(data.locale)) {
new_locale_link.addClass(data.locale);
}
$('#locale_pop').slideDown('slow', function(){
var hide_blip = setTimeout(function(){
$('#locale_pop').slideUp('slow', function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',1,360);
}
else if (show_blip_count < 3 ) {
var b_count = show_blip_count;
b_count ++;
eraseCookie('show_blip_count');
createCookie('show_blip_count',b_count,360);
}
});
},10000);
$('#locale_pop').hover(function(){
clearTimeout(hide_blip);
},function(){
setTimeout(function(){$('#locale_pop').slideUp();},10000);
});
});
},1000);
}
}
});
}
This will help you ALOT!
jQuery Cookie Plugin
I use this all the time. Very simple to learn. Has all the necessary cookie functions built-in and allows you to use a tiny amount of code to create your cookies, delete them, make them expire, etc.
Let me know if you have any questions on how to use (although the DOCS have a decent amount of instruction).