What's wrong in this JavaScript code? - javascript

I can't figure it out..
Markup:
<form>
<fieldset><p>
<label>Username: <input type="text" name="user" id="user" /></label></p><br /><p>
<label>Password: <input type="password" name="passw" id ="passw" /></label></p>
<label><input type="submit" value="Log in" name="submitBUT" style="width: 65px; height: 25px; background-color: green; color: white; font-weight: bold;" id="submitBUT" /><div id="helllo"></div></label>
</fieldset>
</form>
Code:
var subBut = document.getElementById('submitBUT');
var users = ['hithere', 'Peter112', 'Geksj', 'lOsja', 'fInduS', '323DssaAA', 'f1fsus'];
var passes = ['mllesl', 'Petboy', 'Heneeesh', 'Olga', '234dasdf77/', 'minls', 'ew832ja'];
var output = [];
function submi(u, p) {
for (var i = 0; i < users.length; i++) {
if (users[i] == u) {
output.push(i);
}
}
for (var o = 0; o < output.length; o++) {
if (passes[output[o]] == p) {
return p + ' was a correct password.';
}
}
return 'Error, please try again';
}
subBut.onclick = (document.getElementById('helllo').innerHTML=(submi(document.getElementById('user').value, document.getElementById('passw').value)));
LIVE CODE; http://jsfiddle.net/w87MS/
and yes, I know you don't store passwords in the source code :D, it's just "fur t3h lulz"

I have to agree with comments above, not sure what you're doing but...the problem is that a submit handler is a function not the string you're assigning, this:
subBut.onclick = (document.getElementById('helllo').innerHTML=(submi(document.getElementById('user').value, document.getElementById('passw').value)));
should be:
subBut.onclick = function() {
document.getElementById('helllo').innerHTML=
submi(document.getElementById('user').value, document.getElementById('passw').value);
return false; //for testing, prevent form submission
};
You can test the updated version here.

Related

How I store the input.value of two or more dynamic inputs and, with a radio input, select one of all dynamic inputs and store it separately?

Well, I want the Buddy Level [ i ] to be stored outside the iteration and also if it has the active radio input selected, stored separately. Something like "Active buddy Level = X" and "Buddy nº [ i ] Level = Y"
//buddy input
let buddy = document.getElementById("companion")
//buddy lvl inputs
let buddyResult = document.getElementById("companion-inputs")
//funcion que crea inputs dinámicos (text + radio)
function createResult(){
buddyResult.innerHTML = "";
for (let i = 1; i <= buddy.value; i++) {
const element = buddy.value[i];
buddyResult.innerHTML +=
`<div class= "lvl-check">
<input class="clases" id="companion-${i}" type="number" placeholder="Buddy nº${i} lvl"/>
<input type="radio" name="active" />
<label for="companion-${i}">active</label>
</div>`;
}
}
.lvl-check{
display: flex;
align-items: center;
}
.clases{
font-size: 1em;
font-family: "Nunito", sans-serif;
text-align: center;
margin-bottom: 6px;
padding: 6px 12px;
border-radius: 4px;
}
<!--al poner un número, se generan X inputs-->
<input onchange="createResult()" class="clases" id="companion" type="number" placeholder=" Nº of buddies"/>
<!--aqui dentro se generan los inputs dinámicos con los radio-->
<div id="companion-inputs">
</div>
You can try the following script code:
let buddy = document.getElementById("companion");
let buddyResult = document.getElementById("companion-inputs");
let results = {};
let count = 0;
function getResult(id) {
let el = document.getElementById(`${id}`);
results[id] = el.value;
}
function createResult(event) {
console.log("results", results);
for (let i = 1; i <= buddy.value; i++) {
count++;
const element = buddy.value[i];
buddyResult.innerHTML += `<div id="lvl-check">
<input class="clases" id="${count}"
onchange="getResult(${count})"
value="${results[count]}"
type="number"
placeholder="Buddy ${i} level"
/>
<input type="radio" name="${count}" />
<label for="${count}">active</label>
</div>`;
}
}
You can add a data-something attribute to the radio so you can identify its corresponding input. I also refactored my solution a little so you can print or pass the value of a radio using a callback.
let buddy = document.getElementById("companion")
let buddyResult = document.getElementById("companion-inputs")
function createResult() {
for (let i = 1; i <= buddy.value; i++) {
const element = buddy.value[i];
buddyResult.innerHTML += `<div id="lvl-check"><input class="clases" id="companion-${i}" type="number" placeholder="Buddy ${i} level"/><input type="radio" name="active" data-companion-id="companion-${i}"/><label for="companion-${i}">active</label></div>`
}
document.querySelectorAll("#companion-inputs [type=radio]").forEach(function(radio) {
radio.addEventListener('click', function(ev) {
get_value(this, console.log)
});
})
}
function get_values() {
document.querySelectorAll("#companion-inputs [type=radio]").forEach(function(radio) {
console.log(get_value(radio));
})
}
function get_value(radio, foo) {
var id = radio.getAttribute('data-companion-id');
var value = document.getElementById(id).value;
if (typeof foo === 'function') {
foo(value)
}
return value;
}
<input onchange="createResult()" class="clases" id="companion" type="number" placeholder="Amount of gardening companions" />
<div id="companion-inputs"></div>
<button onclick="get_values()">print values</button>

Cognitive complexity reduce issue

i made a login system with JavaScript for a game idea i had, but apparently my ide says it is too complex, do i need to split one function in more pieces? Do it reduces computer processing time? I just don't know if it's critical or not.
Anyway this is the code:
class Log {
constructor() {
this.list = {
username: ["admin", "helper"],
password: ["admin", "h24"]
};
this.user = document.getElementById('username');
this.psw = document.getElementById('password');
this.posUser = null;
this.posPsw = null;
this.t = true;
}
login() {
if (this.user.value != '' && this.user.value != null) {
if (!this.list.username.includes(this.user.value.toLowerCase())) {
errors.innerHTML = 'This user does not exist.';
} else {
for (let i = 0; i < this.list.username.length; i++) { //user[pos]
let j = this.user.value.toLowerCase();
if (j === this.list.username[i]) {
this.posUser = i;
}
}
for (let k = 0; k < this.list.password.length; k++) { //psw[pos]
let l = this.psw.value;
if (l === this.list.password[k]) {
this.posPsw = k;
}
}
if (this.posUser === this.posPsw) {
//access
console.log('access');
} else { // user[pos] != psw[pos] then show error
errors.innerHTML = 'Incorrect password.';
}
}
}
}
}
let errors = document.querySelector('.error');
let invite = new Log();
document.querySelector('.btnLog').addEventListener('click', function() {
invite.login();
});
* {
margin: 5px;
}
<div class="form">
<div class="inline">
<label>user</label><input type="text" id="username" autocomplete="off" />
</div>
<div class="inline">
<label>psw</label><input type="password" id="password" autocomplete="off" />
<div class="eye"></div>
</div>
<div class="flex-start">
<button class="btn btnLog">login</button>
</div>
<div class="inline none -error">
<div class="err_img"></div>
<div class="error"></div>
</div>
</div>
If your IDE uses Sonar to compute the cognitive complexity i suggest you to break up your code in multiple method calls
read this blog post to find out more https://blog.sonarsource.com/cognitive-complexity-because-testability-understandability

How to have all errors pointed out instead of one by one

Here's the cobbled script. It works as in the minute you leave something blank, it points it out via the submit button. But it's annoying because it points it out one by one instead of right away all fields that are blank.
How do I fix this? Please break it down in bite-size as the bigger goal here is understanding it not just merely making this work.
document.forms[0].onsubmit= function() {
var form = document.forms[0];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value.length == 0) {
console.log(form.elements[i]);
form.elements[i].border = "1px solid red";
form.elements[i].style.backgroundColor = "#FFCCCC";
return false;
}
}
}
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="email" name="Email" ></label></p>
<p><input type="submit" value="Submit"></p>
</form>
Your return statement is causing the loop to halt early. Just let it run to the end if you want to signal all incomplete fields.
document.forms[0].onsubmit= function(event) {
for (var i = 0; i < this.elements.length; i++) {
if (this.elements[i].value.length == 0) {
event.preventDefault();
this.elements[i].style.border = "1px solid red";
this.elements[i].style.backgroundColor = "#FFCCCC";
}
}
}
And here's a more modern way to write it, using a class and newer syntax.
document.querySelector("form").addEventListener("submit", function(event) {
for (const el of this.elements) {
if (el.classList.toggle("incomplete", el.value.length == 0)) {
event.preventDefault();
}
}
});
.incomplete {
border: 1px solid red;
background-color: #FFCCCC;
}
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="email" name="Email" ></label></p>
<p><input type="submit" value="Submit"></p>
</form>
You exit the loop as soon as an input element of the form has a length of 0 :
if (form.elements[i].value.length == 0) {
.. ..
return false;
}
The return false; must be located after the loop if at least an input didin't match to your requirements.
You may use a boolean variable to store this information.
<script>
document.forms[0].onsubmit= function() {
var form = document.forms[0];
var hasError = false;
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value.length == 0) {
console.log(form.elements[i]);
form.elements[i].border = "1px solid red";
form.elements[i].style.backgroundColor = "#FFCCCC";
hasError = true;
}
}
if (hasError){
return false;
}
}
</script>

Remove line with specific word from text area using javascript

I am trying to remove line with specific word using javascript from textarea.
Here is example
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
If the user enters the value in input field the line which contains it should be removed. Suppose user enters CxPh1tgiK2g or xOYPv7CxMVk the line which contains those ids should be removed
Try
$("#remove").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
lines = lines.filter(function(val) {
if (val.match(text)) return false
else return true
})
$('#textarea').text(lines.join('\n'))
})
$("#replace").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
var n = Math.floor(Math.random()*lines.length)
lines[n] = lines[n].replace(/\?v=([A-Za-z0-9]){11}/, "?v="+text)
$('#textarea').text(lines.join('\n'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />
<input type="button" id="remove" value="Remove" />
<input type="button" id="replace" value="Replace" />
<br/>
<textarea id="textarea" rows="4" cols="150">
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
As solution to remove line with inclusion
var value = test.value.split(/\n/g).filter(function(val)
{
return val !== "";
});
console.log(value);
setTimeout(function()
{
var index = value.findIndex(function(val)
{
return val.includes('kKC7-ACrs1w');
});
if (index !== -1)
{
value.splice(index, 1);
test.value = value.join("\n");
}
}, 2000);
.text {
width: 100%;
resize: none;
height: 200px;
}
Line with <b>kKC7-ACrs1w </b>will be removed in 2 secs
<textarea name="" id="test" class=text >
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
You can do something like this:
var ta = document.querySelector("textarea");
var lines = ta.innerHTML.split("\n");
var id = "omg";
for (var i = 0; i < lines.length; i ++) {
if (lines[i].indexOf(id) > -1) {
lines.splice(i, 1);
}
}
ta.innerHTML = lines.join("\n");
<textarea>
lol
omg
js
</textarea>

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

Categories