JavaScript code wont execute but get printed as part of html - javascript

I have this html code with js inside and every time i submit the js wont execute but get printed as html, saw many similar problems on stack overflow they said something about not closing <div> correctly but i cant find the error on my code
This is my html code:
<div class="container-fluid">
<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
<div class="form-group row d-flex" style="margin-bottom: 20px;" >
<div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
**filter()**
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
</div>
and this is my js code:
<script>
function filter() {
if(isadmin === 1){
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = false;
document.getElementById('seq').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}else{
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = true;
document.getElementById('pathi').disabled = true;
document.getElementById('scripti').disabled = true;
document.getElementById('Edito').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('scripti').disabled = false;
document.getElementById('Edito').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}
console.log(Boolean(isadmin));
console.log("HYRI KETU");
}
</script>
The html code it was written by someone else i just added the function filter and thats the the code that is being printed as html on the website.

I think that you are missing 3 div closing tags, and that is why your script is being read as html.
//1<div class="container-fluid">
//2<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
//3 <div class="form-group row d-flex" style="margin-bottom: 20px;" >
//4 <div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
filter()
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
//1 </div>
//2 </div> //this and below are added by me
//3</form>
//4 </div>
//5 </div>

Related

why javascript-ajax submitting form multiple times

I am doing single page app. If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in javascript code?
here is my html
function reply_mail(idi) {
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#reply-view').style.display = 'block';
fetch(`/emails/${idi}`)
.then(response => response.json())
.then(email => {
// Print email
var strp = `${email.subject}`;
var ini = 'Re: '
document.querySelector('#reply-recipients').value = `${email.sender}`;
if (strp.slice(0, 4) == 'Re: ') {
document.querySelector('#reply-subject').value = `${strp}`;
} else {
document.querySelector('#reply-subject').value = ini.concat("", strp);
}
var output = `On ${email.timestamp} ${email.sender} wrote:|
${email.body} |
`;
// ... do something else with email ...
document.querySelector('#reply-body').value = output;
// ... do something else with email ...
console.log(email);
});
document.querySelector('#reply-submit').addEventListener('click', function(event) {
event.preventDefault();
rec = document.querySelector('#reply-recipients').value;
sub = document.querySelector('#reply-subject').value;
bod = document.querySelector('#reply-body').value;
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: rec,
subject: sub,
body: bod
})
})
.then(response => response.json())
.then(result => {
// Print result
if ('error' in result) {
console.log(result);
document.querySelector('#reply-error').style.display = 'block';
document.querySelector('#reply-error-i').innerHTML = `<p>${result['error']}</p>`;
} else {
console.log(result);
document.querySelector('#reply-error').style.display = 'none';
load_mailbox('sent');
}
});
})
}
```
<div id="reply-view">
<h3>New Email</h3>
<div class="alert alert-danger" role="alert" id="reply-error">
<div id="reply-error-i">
</div>
</div>
<form id="reply-form">
<div class="form-group">
From: <input disabled class="form-control" value="soham#example.com">
</div>
<div class="form-group">
To: <input id="reply-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="reply-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="reply-body" placeholder="Body"></textarea>
<input type="submit" id="reply-submit" class="btn btn-primary" />
</form>
</div>

Displaying form input on another html page

I am new to javascript and DOM manipulation. So I have this form I have created basically to get names of players. What I want to achieve is to get the player names and display them on the games page once they are redirected after clicking on the button. It does not display the line of code and returns an error:
(VM4444:1 Uncaught ReferenceError: player1 is not defined at
:1:1).
function next() {
var player1 = document.getElementById('play1').value;
var player2 = document.getElementById('play2').value;
if (player1 === '' || player2 === '') {
document.getElementById("error").style.color = "red";
document.getElementById("error").innerHTML = "Please enter both names";
} else {
location.href = "game.html";
}
document.getElementById('name1').innerHTML = player1.value;
document.getElementById('name2').innerHTML = player2.value;
console.log(player1, player2);
}
<div class="col-lg-4 col-md-4 col-sm-12 form">
<form>
<small class="form-text text-muted">We'll never share your details with anyone else.</small>
<div class="form-group">
<label for="player1">Player 1</label>
<input type="text" class="form-control" id="play1" aria-describedby="play1help">
</div>
<div class="form-group">
<label for="player1">Player 2</label>
<input type="text" class="form-control" id="play2" aria-describedby="play1help">
</div>
</form>
<button class="btn btn-lg btn-primary btn-block mt-3" onclick="next();">Start</button>
</div>
Using localStorage you can easily achieve this,
localStorage["key"] = value;
In next page you can get the value by using
value = localStorage["key"];
First Page
function next() {
var player1 = document.getElementById('play1').value;
var player2 = document.getElementById('play2').value;
if (player1 === '' || player2 === '') {
document.getElementById("error").style.color = "red";
document.getElementById("error").innerHTML = "Please enter both names";
} else {
location.href = "game.html";
}
document.getElementById('name1').innerHTML = player1.value;
document.getElementById('name2').innerHTML = player2.value;
localStorage["player1"] = player1;
localStorage["player2"] = player2;
console.log(player1, player2);
}
Next Page
function getPlayer() {
player1 = localStorage["player1"];
player2 = localStorage["player2"];
console.log(player1,player2)
}

Two parameters on a function

I'm trying to make a button onclick event jump to another function if input fields is empty. The function inside the if-statement should have two parameter(one array, one string variable). The function is looping trough all input elements and check if they have a value, if not then add text to a variable that later on is assign to a p-element with .innerHTML.
It worked with only the input parameter, but when I tried to add msg, it stopped working. Maybe it's a simple reason, but I am new to this.
How can I make this work?
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
var msg = "";
btnCreate.onclick = function() {
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
emptyInputs(inputs,msg);
}
message.innerHTML = msg;
}
function emptyInputs(input,text) {
for(var i = 0; i < input.length; i++) {
if (input[i].value === "") {
if(!text) {
missing();
}
text += "- " + input[i].name + "<br />";
}
function missing() {
text = "<strong>Please type in:</strong> <br />";
}
}
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>
You were very close to solving your problem. The only thing is, JavaScript doesn't have ouput params.
When you pass an object or array you can modify the content and those changes will be reflect in your calling method. But this doesn't work for strings. Whatever the value of the string is when you use it as a param to call your method, it will still be the value no matter what your method does to it.
var
array = ['hello'],
object = { hello: true },
string = 'hello';
function modifyArray(inputArray) {
inputArray.push('bye');
}
function modifyObject(inputObject) {
inputObject.bye = true;
}
function modifyString(inputString) {
inputString += ', bye';
}
modifyArray(array);
modifyObject(object);
modifyString(string);
// This will print hello and bye
console.log('Content of array after calling method: ', array);
// This will print hello and bye
console.log('Content of object after calling method: ', object);
// This will just print hello
console.log('Content of string after calling method: ', string);
To solve your problem, create a text string inside the method that builds the error message and return that string as the method result.
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
btnCreate.onclick = function() {
var
// Initialize the error message to an empty string.
msg = '';
// Check if either of the inputs is empty...
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
// ... and get a custom message prompting the user to fill in the empty data.
msg = emptyInputs(inputs);
}
// Display the error message, or clear it when msg is an empty string.
message.innerHTML = msg;
}
function emptyInputs(input) {
// Initialize the error text.
var
missingPrompt = "<strong>Please type in:</strong> <br />",
text = '';
// Iterate over the provided input elements.
for(var i = 0; i < input.length; i++) {
// Check if the value of the current input is an empty string...
if (input[i].value === "") {
// ... check if the error text is still empty...
if(text === '') {
// ... and if it is start with a default message.
text = missingPrompt;
}
// ... add the field name to the error message.
text += "- " + input[i].name + "<br />";
}
}
// Return the error message.
return text;
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>
Here is the code without msg parameter, and it's working just fine.
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
var msg = "";
btnCreate.onclick = function() {
msg = "";
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
emptyInputs(inputs);
}
message.innerHTML = msg;
}
function emptyInputs(input) {
for(var i = 0; i < input.length; i++) {
if (input[i].value === "") {
if(!msg) {
missing();
}
msg += "- " + input[i].name + "<br />";
}
function missing() {
msg = "<strong>Please type in:</strong> <br />";
}
}
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>

Separating HTML and JS

I am trying to separate some JS code that is embedded in to a HTML file. I do not own this code, it is for a remote support landing page but I'm not sure how to separate them out.
I have tried copying the JS code in to a different .js file and then adding the script tags to link but no luck.
<script type="text/javascript" src="https://www.islonline.net/webapi/api.js?
libs=join"></script>
<div class="isl-connect-form">
<form id="isl-connect-form" action="#" method="get" onsubmit="return
isl_connect();">
<fieldset>
<legend>Enter your session code and click Connect</legend>
<div>
<label for="isl-code-field">Session code</label>
<input type="text" name="code" id="isl-code-field" value="" />
</div>
<input type="submit" name="submit" value="Connect" />
</fieldset>
</form>
<div id="isl-feedback"></div>
</div>
<script type="text/javascript">
function isl_connect() {
var doc = document,
f = doc.getElementById('isl-connect-form'),
r = doc.getElementById('isl-feedback'),
is_msie = navigator.userAgent.indexOf('MSIE') >= 0,
b = null;
ISLOnline.Join.getSessionInfoByCode(
f.code.value,
function (info) {
r.className = 'isl-success';
r.innerHTML = 'Connecting to session ' +
info.getAttribute('sessionCode');
if (is_msie) {
r.innerHTML += ', please click the button below:<br />';
r.appendChild(doc.createElement('br'));
var b = doc.createElement('input');
b.type = 'button';
b.name = 'join';
b.value = 'Start';
b.onclick = function () {
info.join();
};
r.appendChild(b);
} else {
info.join();
}
},
function (error) {
r.className = 'isl-error';
r.innerHTML = 'Invalid session code!';
/* comment the line above and uncomment the line below if you
wish to
display the error that is sent by the server */
//r.innerHTML += error.getDescription();
}
);
return false;
}
Create a new JS file and put the original full javascript within it then load it after the islonline.net API call. I have shown an example.
<script type="text/javascript" src="https://www.islonline.net/webapi/api.js?libs=join"></script>
<div class="isl-connect-form">
<form id="isl-connect-form">
<fieldset>
<legend>Enter your session code and click Connect</legend>
<div>
<label for="isl-code-field">Session code</label>
<input type="text" name="code" id="isl-code-field" value="" />
</div>
<input type="submit" name="submit" value="Connect" />
</fieldset>
</form>
<div id="isl-feedback"></div>
</div>
<!-- your new external JS file -->
<script type="text/javascript" src="https://www.example.com/path/to/your/file.js"></script>
Your new Javascript file will contain the original JS code, with a slight modification to help separate HTML and JavaScript by using addEventListener instead of onsubmit:
document.getElementById('isl-connect-form').addEventListener('submit', function isl_connect(event) {
if (typeof event.preventDefault == 'function') event.preventDefault();
var doc = document,
f = this,
r = doc.getElementById('isl-feedback'),
is_msie = navigator.userAgent.indexOf('MSIE') >= 0,
b = null;
ISLOnline.Join.getSessionInfoByCode(
f.code.value,
function (info) {
r.className = 'isl-success';
r.innerHTML = 'Connecting to session ' +
info.getAttribute('sessionCode');
if (is_msie) {
r.innerHTML += ', please click the button below:<br />';
r.appendChild(doc.createElement('br'));
var b = doc.createElement('input');
b.type = 'button';
b.name = 'join';
b.value = 'Start';
b.onclick = function () {
info.join();
};
r.appendChild(b);
} else {
info.join();
}
},
function (error) {
r.className = 'isl-error';
r.innerHTML = 'Invalid session code!';
/* comment the line above and uncomment the line below if you wish to
* display the error that is sent by the server
*/
//r.innerHTML += error.getDescription();
}
);
return false;
});

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Categories

Resources