Mailchimp validation conflicting with Joomla slider - javascript

I am trying to embedd Mailchimp subscribe form on my Joomla site. However, it is conflicting with my 'Gavick PhotoSlide GK2'. to prevent this happened, I need to use the 'Naked form(no css or javascript)'. This will tick the user over to the MailChimp signup page when subscribing. But is it possible to have the validation working inline and not conflicting with my slider? This is the code:
<!-- Begin MailChimp Signup Form -->
<link href="http://cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css" />
<style type="text/css"><!--
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
--></style>
<div id="mc_embed_signup"><form action="http://thetrustsstadium.us4.list-manage1.com/subscribe/post?u=xxx&id=xxx" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group"><label for="mce-EMAIL">Email Address <span class="asterisk">*</span> </label> <input name="EMAIL" class="required email" id="mce-EMAIL" type="email" /></div>
<div class="mc-field-group"><label for="mce-FNAME">First Name <span class="asterisk">*</span> </label> <input name="FNAME" class="required" id="mce-FNAME" type="text" /></div>
<div class="mc-field-group"><label for="mce-LNAME">Last Name <span class="asterisk">*</span> </label> <input name="LNAME" class="required" id="mce-LNAME" type="text" /></div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<div class="clear"><input value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" type="submit" /></div>
</form></div>
<script type="text/javascript"><!--
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://thetrustsstadium.us4.list-manage.com/subscribe/post-json?u=xxx&id=xxx&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'" mce_style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
// --></script>
<!--End mc_embed_signup-->

Sure it's possible, but there's no way to tell with just the code you posted. We'll need a link to a test page so we can take a look at the whole thing and see where the conflicts are. Before I spent a bunch of time messing with it though, I would try this component -
http://extensions.joomla.org/extensions/content-sharing/mailing-a-newsletter-bridges/13602
It comes with a sign up module and it seems to integrate pretty well with most 3rd party javascript. Try it before you do anything else, it may just work.
Otherwise you will likely have to rewrite the validation or switch to server side validation in order to fix the conflict.

Related

textarea isn't reading input that I have made [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">

Javascript make event click and speech recognition work with multiple buttons

So I am using webkitSpeechRecognition and it works great, but the problem is I want to use it in multiple places at the same time and when I add it into another section on my page it doesn't work correctly.
Here is it working on its own:
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
//get languages
// https://gist.githubusercontent.com/onigetoc/d5dc63320c4d08633eb7b7daf6c1ddeb/raw/e9c3da4a40db8edf4992db9219526617da811c4c/lang.json
$.get("//raw.githubusercontent.com/the-creature/language-json/master/data.json", function(data) {
var cList = $('#language');
var data = $.parseJSON(data);
$.each(data, function(i) {
var option = $('<option/>')
.attr('value', data[i].code)
.html(data[i].name)
.appendTo(cList);
});
var userLang = navigator.language || navigator.userLanguage;
$("#language").val(userLang);
});
// Speech Recognition
if (!('webkitSpeechRecognition' in window)) {
message.innerHTML = 'Web Speech API is not supported by this browser. Upgrade to Chrome version 25 or later.';
} else {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
message.innerHTML = 'Speak now.';
talk_button.innerHTML = 'Listen';
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
vc_search(final_transcript);
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_span.innerHTML = final_transcript;
interim_span.innerHTML = interim_transcript;
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
speechMyText(final_transcript);
if (!final_transcript) {
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
message.innerHTML = 'No speech was detected.';
ignore_onend = true;
}
if (event.error == 'audio-capture') {
message.innerHTML = 'No microphone was found. Ensure that a microphone is installed.';
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
message.innerHTML = 'Permission to use microphone is blocked. To change, go to chrome://settings/contentExceptions#media-stream';
} else {
message.innerHTML = 'Permission to use microphone was denied.';
}
ignore_onend = true;
}
};
}
function talkWithApp(event) {
if (recognizing) {
recognition.stop();
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
final_transcript = '';
recognition.lang = language.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
message.innerHTML = 'Click the "Allow" button above to enable your microphone.';
start_timestamp = event.timeStamp;
}
// Speech Synthesis
function speechMyText(textToSpeech) {
var u = new SpeechSynthesisUtterance();
u.text = textToSpeech;
u.lang = language.value;
u.rate = 1.0;
u.onend = function(event) {}
speechSynthesis.speak(u);
}
.message {
color:#999;
padding: 1em 0;
}
.todo, .response {
min-height:50px;
background-color: #fff;
margin-bottom: 0.5em;
padding: 1px;
color:#555;
-webkit-box-shadow: 0 0px 3px #BDBDBD;
box-shadow: 0 0px 3px #BDBDBD;
transition: all 0.3s ease-in-out;
}
<div class="container">
<div id="message" class="message">Click "Talk" and begin speaking.</div>
<div class="todo"> <span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<div class="controls">
<button id="talk_button" type="button" class="btn btn-default" onclick="talkWithApp(event)">Talk</button>
<select id="language" class="select">
<option selected="selected">Select Your Language</option>
</select>
</div>
</div>
And here is it running multiple times within the same page:
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
//get languages
// https://gist.githubusercontent.com/onigetoc/d5dc63320c4d08633eb7b7daf6c1ddeb/raw/e9c3da4a40db8edf4992db9219526617da811c4c/lang.json
$.get("//raw.githubusercontent.com/the-creature/language-json/master/data.json", function(data) {
var cList = $('#language');
var data = $.parseJSON(data);
$.each(data, function(i) {
var option = $('<option/>')
.attr('value', data[i].code)
.html(data[i].name)
.appendTo(cList);
});
var userLang = navigator.language || navigator.userLanguage;
$("#language").val(userLang);
});
// Speech Recognition
if (!('webkitSpeechRecognition' in window)) {
message.innerHTML = 'Web Speech API is not supported by this browser. Upgrade to Chrome version 25 or later.';
} else {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
message.innerHTML = 'Speak now.';
talk_button.innerHTML = 'Listen';
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
vc_search(final_transcript);
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_span.innerHTML = final_transcript;
interim_span.innerHTML = interim_transcript;
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
speechMyText(final_transcript);
if (!final_transcript) {
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
message.innerHTML = 'No speech was detected.';
ignore_onend = true;
}
if (event.error == 'audio-capture') {
message.innerHTML = 'No microphone was found. Ensure that a microphone is installed.';
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
message.innerHTML = 'Permission to use microphone is blocked. To change, go to chrome://settings/contentExceptions#media-stream';
} else {
message.innerHTML = 'Permission to use microphone was denied.';
}
ignore_onend = true;
}
};
}
function talkWithApp(event) {
if (recognizing) {
recognition.stop();
message.innerHTML = 'Click "Talk" and begin speaking.';
talk_button.innerHTML = 'Talk';
return;
}
final_transcript = '';
recognition.lang = language.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
message.innerHTML = 'Click the "Allow" button above to enable your microphone.';
start_timestamp = event.timeStamp;
}
// Speech Synthesis
function speechMyText(textToSpeech) {
var u = new SpeechSynthesisUtterance();
u.text = textToSpeech;
u.lang = language.value;
u.rate = 1.0;
u.onend = function(event) {}
speechSynthesis.speak(u);
}
.message {
color:#999;
padding: 1em 0;
}
.todo, .response {
min-height:50px;
background-color: #fff;
margin-bottom: 0.5em;
padding: 1px;
color:#555;
-webkit-box-shadow: 0 0px 3px #BDBDBD;
box-shadow: 0 0px 3px #BDBDBD;
transition: all 0.3s ease-in-out;
}
<div class="container">
<div id="message" class="message">Click "Talk" and begin speaking.</div>
<div class="todo"> <span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<div class="controls">
<button id="talk_button" type="button" class="btn btn-default" onclick="talkWithApp(event)">Talk</button>
<select id="language" class="select">
<option selected="selected">Select Your Language</option>
</select>
</div>
</div>
<div class="container">
<div id="message" class="message">Click "Talk" and begin speaking.</div>
<div class="todo"> <span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<div class="controls">
<button id="talk_button" type="button" class="btn btn-default" onclick="talkWithApp(event)">Talk</button>
<select id="language" class="select">
<option selected="selected">Select Your Language</option>
</select>
</div>
</div>
As you can see it doesn't work correctly on both when running multiple times. How can I make it so it only uses the section that was clicked? but still works in multiple places on a page.
Here are the two different ways:
https://jsfiddle.net/k5cm8ypg/
https://jsfiddle.net/ygpbfLso/1/
It seems that in your HTML your using ID multiple times; IDs should be unique to a certain page or frame.
Then in your script, both recognition object and your event can't properly get and assign values because an ID they're trying to access has been declared more than once.
What I did was;
Remove all the IDs to use classes
Add a global var activeButton
Bind talk event to the whole document and triggers when .talk_button is clicked.
When .talk_button is clicked, the context is set around that button. This is done with activeButton = $(this);. You will notice I used a combination of .parent(),.find() to find the elements within the context or container of that button.
Run the demo on jsfiddle. It was fun to work with, didn't know there's a speech api readily available on the browser.
https://jsfiddle.net/1pvqx2am/2/

Unable to retain the table values after refreshing the browser window

Created a form using html, javascript. After entering the fields, when i click submit button, it saves the user data in localstorage and updates the table rows dynamically. But once i refresh the browser, the table holding the information of all users is lost. I want to retain the table after refreshing the browser.
Click here to view screenshot of page Before refresh
Click here to view screenshot of page After refresh
JS Code :
var testObject = [];
var users = {};
function clear(){
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username,usermail,password,location,organization,gender){
if(username!="" && usermail!="" && password!="" && location!="" && organization!="" && gender!=""){
return true;
}
}
function removeDivChild(str)
{
if(document.getElementById(str).querySelector('p')){
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val,cdiv)
{
if(val=="" && document.getElementById(cdiv).querySelector('p')==null)
{
var node = document.createElement("P");
if(document.getElementById(cdiv).className=="textbox"){
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
}
else if(document.getElementById(cdiv).className=="radiobox"){
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if(val!="" && document.getElementById(cdiv).querySelector('p')!=null)
{
document.getElementById(cdiv).lastElementChild.remove();
}
}
function save(){
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if(document.getElementById("m").checked){
genval = document.getElementById("m").value;
}
if(document.getElementById("f").checked)
{
genval = document.getElementById("f").value;
}
if(IsValid(userval,eval,passval,locval,orgval,genval))
{
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
updateTable();
}
else
{
appendToDiv(userval,"userdiv");
appendToDiv(eval,"maildiv");
appendToDiv(passval,"passdiv");
appendToDiv(locval,"locdiv");
appendToDiv(orgval,"orgdiv");
appendToDiv(genval,"gendiv");
}
}
function updateTable(){
localStorage.setItem("user", JSON.stringify(testObject));
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
if(i==0){
var nodeh = document.createElement("tr");
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
nodeh.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
nodeh.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
nodeh.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
nodeh.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
nodeh.appendChild(onode);
var gnode = document.createElement("th");
var gtext = document.createTextNode("gender");
gnode.appendChild(gtext);
nodeh.appendChild(gnode);
document.getElementById("t").appendChild(nodeh);
}
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
var nodeg = document.createElement("td");
var textg = document.createTextNode(usr[i].gender);
nodeg.appendChild(textg);
noder.appendChild(nodeg);
document.getElementById("t").appendChild(noder);
clear();
}
HTML code :
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="check.js"></script>
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male"/> Male
<input type="radio" name="gender" id="f" value="female"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
After the back and forth in the comments on your question I decided to just create an example from your code sample. Most of it was untouched however I did add comments to the things that I did change.
// I moved the declaration of the testObject below to let the functions be created first
// so i can use teh new loadFromStorage function to create the object
var users = {};
// This is a new function I created
function loadFromStorage() {
// parse the 'user' object in local storage, if its empty return an empty array
return JSON.parse(localStorage.getItem('user')) || [];
}
function clear() {
// I didn't touch this function
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username, usermail, password, location, organization, gender) {
// I didn't touch this function
if (username != "" && usermail != "" && password != "" && location != "" && organization != "" && gender != "") {
return true;
}
}
function removeDivChild(str) {
// I didn't touch this function
if (document.getElementById(str).querySelector('p')) {
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val, cdiv) {
// I didn't touch this function
if (val == "" && document.getElementById(cdiv).querySelector('p') == null) {
var node = document.createElement("P");
if (document.getElementById(cdiv).className == "textbox") {
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
} else if (document.getElementById(cdiv).className == "radiobox") {
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if (val != "" && document.getElementById(cdiv).querySelector('p') != null) {
document.getElementById(cdiv).lastElementChild.remove();
}
}
// Changes in this function
function save() {
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if (document.getElementById("m").checked) {
genval = document.getElementById("m").value;
}
if (document.getElementById("f").checked) {
genval = document.getElementById("f").value;
}
if (IsValid(userval, eval, passval, locval, orgval, genval)) {
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
// Saving testObject to the persistent storage here because this is where it belongs
localStorage.setItem("user", JSON.stringify(testObject));
updateTable();
} else {
appendToDiv(userval, "userdiv");
appendToDiv(eval, "maildiv");
appendToDiv(passval, "passdiv");
appendToDiv(locval, "locdiv");
appendToDiv(orgval, "orgdiv");
appendToDiv(genval, "gendiv");
}
}
// Changes in this function
function updateTable() {
// pulled out the saving and the loading of user from localStorage here,
// everything should already be saved or loaded by the time we call
// this function.
// Also re-wrote this function because it was messy and hard to read, always remember you write code for humans not computers so slightly longer variable names that are descriptive are really good.
// get a reference to the table
var tbl = document.getElementById('t');
// remove all the child rows, except for the header
// CSS Selector explained:
// #t - find the table by the id (you used t)
// > tr > td - find all td's that are direct children of the t table
Array.prototype.forEach.call(document.querySelectorAll('#t > tr > td'), function(node) {
node.parentNode.removeChild( node );
})
// loop over all the 'users' in 'testObject'
for(var i = 0; i < testObject.length; i++){
// store a reference to the current object to make the code easier to read
var currentObject = testObject[i];
// create the TR
var tr = document.createElement('tr');
// Create the td's
var tdUserName = document.createElement('td');
var tdEmail = document.createElement('td');
var tdPassword = document.createElement('td');
var tdLocation = document.createElement('td');
var tdOrganization = document.createElement('td');
var tdGender = document.createElement('td');
// create the text nodes
var userName = document.createTextNode(currentObject.uname);
var email = document.createTextNode(currentObject.email);
var password = document.createTextNode(currentObject.pass);
var location = document.createTextNode(currentObject.loc);
var organization = document.createTextNode(currentObject.org);
var gender = document.createTextNode(currentObject.gender);
// add the elements to their containers
tdUserName.appendChild(userName);
tdEmail.appendChild(email);
tdPassword.appendChild(password);
tdLocation.appendChild(location);
tdOrganization.appendChild(organization);
tdGender.appendChild(gender);
// add the td's to the row
tr.appendChild(tdUserName);
tr.appendChild(tdEmail);
tr.appendChild(tdPassword);
tr.appendChild(tdLocation);
tr.appendChild(tdOrganization);
tr.appendChild(tdGender);
// add the row to the table
tbl.appendChild(tr);
}
// call your clear function
clear();
}
// load the object from storage
var testObject = loadFromStorage();
// populate the table
updateTable();
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male" /> Male
<input type="radio" name="gender" id="f" value="female" /> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<!-- Added the header to the table, it isn't removed now when rebuilding it -->
<table id="t" border="1">
<thead>
<tr>
<td>Username</td>
<td>Email</td>
<td>Password</td>
<td>Location</td>
<td>Organization</td>
<td>Gender</td>
</tr>
</thead>
</table>
Here is a link to a JSFiddle because this example wont run properly because it accesses localStorage but is sandboxed. Working Example

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

onSubmit validation changing label style

I'm trying to get this form to change label color after submission if the field is empty and then return back to normal when the field is filled in.
It's behaviour would be something similar to:
Onsubmit validate change background requried fields?
Except I can't figure out how to link the inputs to the labels. I'm using the jsFiddle from the link above at:
http://jsfiddle.net/interdream/cpG2r/7/
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
My JavaScript isn't so good. Please help!
Here is your Working sample</>
You should look around Knockoutjs style binding with dom value.
you could add label tags, like:
<form action="" id="myForm">
<label for="field1">Required field:</label> <input type="text" name="field1" class="required" /><br />
<label for="field2">Required field 2:</label> <input type="text" name="field2" class="required" />
<input type="submit" value="Go" />
</form>
And in js part
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
var lbl = document.getElementsByTagName("label")[i]; //get label
if(!fields[i].value) {
lbl.style.color = "red";
console.log(lbl );
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
lbl.style.color = "black";
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
See : updated Fiddle
Try
<form action="" id="myForm">
<label>Required field: </label><input type="text" class="required" /><br />
<label>Required field 2: </label><input type="text" class="required" />
<input type="submit" value="Go" />
</form>
And
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
var prev = fields[i].previousSibling;
while(!/label/i.test(prev.tagName)){
prev = prev.previousSibling;
}
prev.style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
Demo: Fiddle
You can use jquery validation Plugin ... it has support for all types of validations as well as changing label colors & Can display suitable error messages
Here is very simple, smart yet effective way to doing this by using amazing knockout binding here is working sample :JsFiddle Link
var viewModel = {
validation: ko.observable(function(){})
};

Categories

Resources