JS | do-while - guess number | wrong output - javascript

I have a problem with the do-while. When I type into an input form a different number than 15, it still says 'success', but it shouldn't, because the right number is 15. How could I change the do-while to recognize when I type other number than 15? Thanks for any suggestions.
//works when type only 15
do {
var guess = prompt("Guess a number between 1 and 20");
} while (guess !=15)
alert("Success!");
//this part works when I type 15 or different number
function guessWage() {
do {
var guess = document.getElementById("guessNumber")
if (guess.value != 15) {
guess.value = false;
}
} while (guess.value === 15)
alert('you guessed the number');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>While loop</h2>
<h5><span class="badge badge-secondary">Array backwards:</span></h5>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<h5><span class="badge badge-secondary">Array forwards:</span></h5>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<h5><span class="badge badge-secondary">Guess, how much full-stack dev earns</span></h5>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">$</span>
<input type="text" class="form-control" placeholder="Type the number" aria-label="Number" aria-describedby="basic-addon1" id="guessNumber">
</div>
<button onclick="guessWage()" type="button" class="btn btn-info">Guess it!</button>
</div>
<!-- Scripts -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="whileloop.js"></script>
</body>
</html>
Ok, I changed the string to Number with Number(var), but now it's giving me an infinite loop. I'm little bit confused. Someone knows what to add into this do-while?
function guessWage() {
do {
var guess = document.getElementById("guessNumber")
} while (Number(guess.value) !== 15)
alert('you guessed the number');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>While loop</h2>
<h5><span class="badge badge-secondary">Array backwards:</span></h5>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<h5><span class="badge badge-secondary">Array forwards:</span></h5>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<h5><span class="badge badge-secondary">Guess, how much full-stack dev earns</span></h5>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">$</span>
<input type="text" class="form-control" placeholder="Type the number" aria-label="Number" aria-describedby="basic-addon1" id="guessNumber">
</div>
<button onclick="guessWage()" type="button" class="btn btn-info">Guess it!</button>
</div>
<!-- Scripts -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="whileloop.js"></script>
</body>
</html>

Javascript uses == !=, but you should always use === and !==.
Since the former can have unpredictable results sometimes. Moreover, you are comparing a string to an integer. Try converting them beforehand using Number(var)

Basically what you are trying to achieve is not clear.. if you simply want to compare the values on button click you dont need a loop in that case.so something like..
function guessWage() {
var guess = document.getElementById("guessNumber")
if (guess.value != "15") {
// do what you want here if guess is wrong.
alert('wrong guess');
}
else
{
// do what you want if guess is right
alert('right guess');
}
}
OR
function guessWage()
{
var guess = document.getElementById("guessNumber")
if (Number(guess.value) != 15) {
// do what you want here if guess is wrong.
alert('wrong guess');
}
else
{
// do what you want if guess is right
alert('right guess');
}
}
feel free to comment about if anything is there i will update my answer.

Related

Prompt the user to type in a character/string and tell whether the input is in a given string

I need to create two functions, to request the user to type in a character and a string.
The inputs are matched with a given string.
Then tell the user, if the input character/string is found in the default given string.
So far I have created the basics to get the user inputs, but couldn't find any method to implement the javascript functions.
Any help would be highly appreciated.
Here's my code so far..!
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width shrink-to-fit=no initial-scale=1">
<title>Web Programming is fun!</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous"
>
<style>
p{display: inline;}
</style>
</head>
<body>
<div class="container">
<h1>Web Programming is Fun!</h1>
<br>
<p>Lets use the above heading string to demonstrate inbuilt methods.</p>
<label for="inputCharacter">Please type a character: </label>
<input type="text" id="inputCharacter">
<button onclick="matchCharacter()">Match Character</button>
<p id="character"></p>
<br>
<label for="inputString">Please type a string: </label>
<input type="text" id="inputString">
<button onclick="matchString()">Match String</button>
<p id="string"></p>
<script>
let text ="Web programming is fun!";
function matchCharacter()
{
var char=document.getElementById("inputCharacer").innerHTML;
if(char.indexOf(text) )
{
alert("Your Character is found in the string!")
}
}
function matchSring()
{
}
</script>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous">
</script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous">
</script>
</body>
</html>
I think you have inverted the parameters. Instead of char.indexOf you should use text.indexOf.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width shrink-to-fit=no initial-scale=1">
<title>Web Programming is fun!</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
crossorigin="anonymous"
>
<style>
p{display: inline;}
</style>
</head>
<body>
<div class="container">
<h1>Web Programming is Fun!</h1>
<br>
<p>Lets use the above heading string to demonstrate inbuilt methods.</p>
<label for="inputCharacter">Please type a character: </label>
<input type="text" id="inputCharacter" maxLength="1">
<button onclick="matchCharacter()">Match Character</button>
<p id="character"></p>
<br>
<label for="inputString">Please type a string: </label>
<input type="text" id="inputString">
<button onclick="matchString()">Match String</button>
<p id="string"></p>
<script>
let text ="Web Programming is Fun!";
function matchCharacter()
{
var char=document.getElementById("inputCharacter").value;
if(text.indexOf(char) != -1)
{
alert("Your Character is found in the string!")
} else {
alert("Your Character is not found in the string!")
}
}
function matchString()
{
var string=document.getElementById("inputString").value;
if(text.indexOf(string) != -1)
{
alert("String Found in heading!")
} else {
alert("String not found in the heading!")
}
}
</script>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous">
</script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous">
</script>
</body>
</html>
Inside your javascript you can replace innerHTML to value attribute to access user input and then match that character.
And also you are calling indexOf on character but you have to call it on the text variable that you have created.
<script>
let text ="Web programming is fun!";
function matchCharacter()
{
var char=document.getElementById("inputCharacer").value;
if(text.indexOf(char) !== -1)
{
alert("Your Character is found in the string!");
return true;
}
return false;
}
function matchSring()
{
if (matchCharacter()) console.log("Character is found");
else console.log("Character is not found");
}
</script>

How to prevent input from displaying in address bar

I want to ask for help from you guys, I have tried coding my javascript so that it doesn't display the results from the input but the results I get are actually messy, so I attach my code with the original version that I haven't edited and it's still tidy, but the input is still displayed in address bar in the web browser.
Next is my code version before revision: (JavaScript)
(function ($) {
"use strict";
/*==================================================================
[ Validate ]*/
var input = $('.validate-input .input100');
$('.validate-form').on('submit',function(){
var check = true;
for(var i=0; i<input.length; i++) {
if(validate(input[i]) == false){
showValidate(input[i]);
check=false;
}
}
return check;
});
$('.validate-form .input100').each(function(){
$(this).focus(function(){
hideValidate(this);
});
});
function validate (input) {
if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') {
if($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
return false;
}
}
else {
if($(input).val().trim() == ''){
return false;
}
}
}
function showValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).addClass('alert-validate');
}
function hideValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).removeClass('alert-validate');
}
/*==================================================================
[ Simple slide100 ]*/
$('.simpleslide100').each(function(){
var delay = 7000;
var speed = 1000;
var itemSlide = $(this).find('.simpleslide100-item');
var nowSlide = 0;
$(itemSlide).hide();
$(itemSlide[nowSlide]).show();
nowSlide++;
if(nowSlide >= itemSlide.length) {nowSlide = 0;}
setInterval(function(){
$(itemSlide).fadeOut(speed);
$(itemSlide[nowSlide]).fadeIn(speed);
nowSlide++;
if(nowSlide >= itemSlide.length) {nowSlide = 0;}
},delay);
});
})(jQuery);
please help me also to place it in the coding that I have made, apologize that I am still a beginner and I'm confused how to do it anymore, all the help will be appreciated :)
This is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>AN Newsletter | Subscribe</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
</head>
<body>
<div class="flex-w flex-str size1 overlay1">
<div class="flex-w flex-col-sb wsize1 bg0 p-l-70 p-t-37 p-b-52 p-r-50 respon1">
<div class="wrappic1">
<a href="../main/index.html">
<img src="images/icons/logo.png" alt="IMG">
</a>
</div>
<div class="w-full p-t-100 p-b-90 p-l-48 p-l-0-md">
<h3 class="l1-txt1 p-b-34 respon3">
Post Box
</h3>
<p class="m2-txt1 p-b-46">
Follow me for update now!
</p>
<form class="contact100-form validate-form m-t-10 m-b-10" action="../success/success.html">
<div class="wrap-input100 validate-input m-lr-auto-lg" data-validate = "Email is required: ex#abc.xyz">
<input class="s2-txt1 placeholder0 input100 trans-04" type="text" name="email" placeholder="Email Address">
<button class="flex-c-m ab-t-r size2 hov1 respon5">
<i class="zmdi zmdi-long-arrow-right fs-30 cl1 trans-04"></i>
</button>
<div class="flex-c-m ab-t-l s2-txt1 size4 bor1 respon4">
<span>Subcribe Now:</span>
</div>
</div>
</form>
</div>
<div class="flex-w flex-m">
<span class="m2-txt2 p-r-40">
Follow me
</span>
<a href="https://www.facebook.com/stevenWilliamG" class="size3 flex-c-m how-social trans-04 m-r-15 m-b-5 m-t-5">
<i class="fa fa-facebook"></i>
</a>
<a href="https://twitter.com/AdrikAleandra" class="size3 flex-c-m how-social trans-04 m-r-15 m-b-5 m-t-5">
<i class="fa fa-twitter"></i>
</a>
<a href="https://www.instagram.com/audynaufal7/" class="size3 flex-c-m how-social trans-04 m-r-15 m-b-5 m-t-5">
<i class="fa fa-instagram"></i>
</a>
<a href="https://www.linkedin.com/in/audy-naufal-ghiffari-ceh-875072141/" class="size3 flex-c-m how-social trans-04 m-r-15 m-b-5 m-t-5">
<i class="fa fa-linkedin"></i>
</a>
</div>
</div>
<div class="wsize2 bg-img1 respon2" style="background-image: url('images/bg01.jpg');">
</div>
</div>
<!--===============================================================================================-->
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/tilt/tilt.jquery.min.js"></script>
<!--===============================================================================================-->
<script src="js/main.js"></script>
</body>
</html>
P.S:
please don't block me, I'm still new and I still have to learn this platform and I still have to work on my project, so I think this platform will be very useful for me to complete my project, thank you
If you are referring to browser address bar with result of your input email address that looks like this:
/success/success.html?email=xxxx
This is because you haven't specified the method of your form so form uses PHP GET, and this is normal to pass the values on other page.
If you do not want to display this data, you should specify your form submit method like this:
<form class="contact100-form validate-form m-t-10 m-b-10"
action="../success/success.html" method="POST">
Keep in mind you have to fetch data on other side as POST also.
Read more about this here.
Replace GET method with POST method.

Progress Bar width to change when increment button clicked. Javascript

Working now
Ok so hello, im looking for help with the code below:
When i click the increment button the values increment by one on each click, which is essentially what i want it do to. But I also want the blue progress bar to fill the bar as the numbers increase.
I have a run able piece of code which may help with de-bugging here below.
All help appreciated as i am new to this site Thanks.
function getProgress() {
return document.getElementById("progressbar").getAttribute("aria-valuenow");
return document.getElementById("progressbar").getAttribute("style","width");
return document.getElementById("progressbar").innerHTML;
}
function setProgress(value) {
document.getElementById("progressbar").setAttribute("aria-valuenow",value);
document.getElementById("progressbar").setAttribute("style","width: " +value+ "%");
document.getElementById("progressbar").innerHTML = (value+ "%");
}
function increment() {
var i = getProgress();
if(i < 100){
i++;
setProgress(i);
}else{
alert("Progress Complete!");
}
}
function decrement() {
var d = getProgress();
setProgress(d - 1);
}
function resetButton() {
var r = getProgress();
setProgress(r = 0);
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<title>Progress Bar</title>
</head>
<body>
<!-- Container -->
<div class="container">
<h1>This Process bar is animated using <br>JavaScript!</h1>
<br>
<!-- Div For Progress Bar -->
<div class="progress">
<div class="progress-bar progress-bar-striped" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="progressbar" >0%</div>
</div>
<br>
<!-- Buttons -->
<button type="button" class="btn btn-primary" onclick = "increment()">Increment</button>
<button type="button" class="btn btn-dark" onclick="resetButton()">Reset</button>
<button type="button" class="btn btn-success" onclick="decrement()">Decrement</button>
<button type="button" class="btn btn-warning" onclick="">Start Auto Progress!</button>
<button type="button" class="btn btn-danger" onclick="">Stop Auto Progress!</button>
<p id="value"> </p>
<!-- End of Container -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="Assignment4.js"></script>
</body>
</html>
You're only missing a single colon in your line to set width. Should be "width: " + value instead.

Add and remove rows in a form with unique id's that returns an object as an array

I already have my own solution for this problem, but then I don't know if I'm using the best techniques/practices to solve this particular scenario, which involves removing and adding DOM elements with unique id's.
I have just used jQuery, the requirements where only a button to add any amount of rows, once another row is added be able to delete that row too, the first row is always mandatory, here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <title>Simple form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
label{
display: block;
}
</style>
</head>
<body>
<div class="container">
<div class="row inputRows">
<div class="col-sm-12" id="newRow-1">
<label>Some label over input</label>
<input type="text" name="txt">
</div>
</div>
<div class="row">
<div class="col-sm-12">
<button id="addRow"><span class="fa fa-plus"></span> Add </button>
<button id="viewInfo"><span class="fa fa-plus"></span> Info </button>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="result">
</p>
</div>
</div>
</div>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
$('.inputRows').on('click', 'button' ,function(){
$(this).parent().remove();
});
$('#addRow').click(function(){
var $newRow = $('div[id^="newRow"]:first').clone(),
newId = Number($('div[id^="newRow"]:last').attr('id').split('-')[1]) + 1;
$newRow.append('<button><span class="fa fa-trash-o"></span></button>');
$newRow.find('input').val('');
$newRow.attr('id','newRow-' + newId);
$('.inputRows').append($newRow);
});
$('#viewInfo').click(function(){
$('#result').text(JSON.stringify(objectifyForm($('div[id^="newRow"]'))));
});
function objectifyForm(formArray) {
var resultArray = {},
inputValue = '';
for (var i = 0; i < formArray.length; i++){
inputValue = $(formArray[i]).find('input').val();
if(inputValue){
resultArray[$(formArray[i]).attr('id')] = inputValue;
}
}
return resultArray;
}
</script>
</body>
</html>
So the code works, the only problem I see is that the numeration of the id's, can sometimes be 1,5,8,7,6,12 depending on which ones you delete, but then it's fine because in the end, it doesn't even matter (joke, RIP Chester, but kind of true). My main concern or question is, is there any other way of achieving this more efficiently using jQuery? Am I doing something wrong by cloning the first element multiple times? If you can share some knowledge on DOM manipulation that would be great.
Thanks in advance,
Leo.

summernote editor not opening (laravel 5.2)

I am using summernote js in laravel 5.2.
In a form,when user clicks on edit button, summernote editor should open for the fields.Actually it was working for a single field but when i applied it for more than one field,its not working.
my view:
<form action="{{route('account')}}" id="acc" class="ac" method="post">
<div class="col-lg-3"><label>Estado</label>
#foreach($accounts as $account)
#if($user== $account->user)
{!! $account->estado !!}
<textarea style="display:none;" name="textfield4" id="textfield4"></textarea>
<div class="col-lg-2 estado " id="estado"></div>
#endif
#endforeach
</div>
<div class="col-lg-4"></div>
</div>
<div class="row">
<section class="col-lg-3 "><label for="textfield5">I'm Good At:</label>
#foreach($accounts as $account)
#if($user== $account->user)
{!! $account->goodat !!}
<textarea style="display:none;" name="textfield5" id="textfield5"></textarea>
<div class="col-lg-2 col-md-2 es" id="goodat"></div>
#endif
#endforeach
<br /><div><button type="button" class="btn btn-info edit">Edit</button>
<button type="submit" class="btn btn-success" id="btn-send-message" >Save</button>
<input type="hidden" value="{{Session::token()}}" name="_token">
</div>
</form>
my script:
<script>
$(document).ready(function() {
var $estado = $('#estado');
var $goodat = $('#goodat');
var edit = function() {
$estado.summernote({focus: true});
$goodat.summernote({focus: true});
};
$('.edit').on('click', edit);
$("#acc").on('submit', function(e) {
e.preventDefault();
var self = this;
// lets check some stuff
console.log($estado);
console.log($estado.summernote('code'));
console.log($('#textfield4'));
console.log($('#textfield4').val());
console.log($('#textfield4').text());
var estado = $estado.summernote('code');
$("#textfield4").val(estado); //populate text area
var goodat = $goodat.summernote('code');
$("#textfield5").val(goodat); //populate text area
self.submit();
return false;
});
});
</script>
EDIT 1:
I've found out that, after clicking on save button ( which results in null values in db)(everytime a user logins) , edit button starts working perfectly.
EDIT 2:
after placing all links and scripts in head tag ,error: $ is not defined .
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="_token" content="{{ csrf_token() }}">
<title>#yield('title')</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700">
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="{{URL::to('src/css/crush.css')}}">
<link rel="stylesheet" type="text/css" href="{{URL::to('src/css/groups.css')}}">
<link rel="stylesheet" type="text/css" href="{{URL::to('src/css/Untitled-2.css')}}">
<link rel="stylesheet" type="text/css" href="{{URL::to('src/css/font-awesome.css')}}">
<link rel="stylesheet" type="text/css" href="{{URL::to('src/css/style.css')}}">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js" ></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
<script src="/src/js/myplace.js"></script>
<script src="{{URL::asset('src/js/script.js')}}"></script>
</head>
You wanted multiple textareas with summernote?
Take: (;
$(function() {
var $estado = $('#estado');
var $goodat = $('#goodat');
var isEditorsActive = false;
function activateEditors() {
$estado.summernote({
focus: true
});
$goodat.summernote({
focus: true
});
isEditorsActive = true;
}
function deactivateEditors() {
$estado.summernote('destroy');
$goodat.summernote('destroy');
isEditorsActive = false;
}
$('button.edit').click(function(e){
e.preventDefault();
(isEditorsActive)? deactivateEditors() : activateEditors();
});
$("form#ac").submit(function(e) {
e.preventDefault();
var $this = $(this);
if(isEditorsActive) {
var estado = $estado.summernote('code');
var goodat = $goodat.summernote('code');
$('#data-estado').html(estado);
$('#data-goodat').html(goodat);
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
<form action="{{route('account')}}" id="ac" class="ac" method="post">
<div class="row">
<div class="col-lg-3">
<label>Estado</label>
#foreach($accounts as $account)
#if($user== $account->user)
<div class="estado" id="estado" style="width:100%">
{!! $account->estado !!}
</div>
#endif
#endforeach
</div>
<div class="col-lg-3"></div>
<div class="col-lg-3">
<label>I'm Good At:</label>
#foreach($accounts as $account)
#if($user==$account->user)
<div class="goodat" id="goodat" style="width:100%">
{!! $account->goodat !!}
</div>
#endif
#endforeach
</div>
</div>
<button type="submit" class="btn btn-success save">Save</button>
<button class="btn btn-default edit">Edit</button>
</form>
ESTADO:
<div id="data-estado">
</div>
GOOD AT:
<div id="data-goodat">
</div>
but after this You still cannot get the data that inside these textareas - so really something is wrong with Your blade template
http://num8er.me/summernote.html
I think you could have some asynchronous issues here, since it works sometimes, and sometimes not. You are setting the value of the textareas based on the values of the summernote fields. You can't be sure though, that $estado.summernote('code') is already finished before using the value of the summernote field to set the value of textfield4 (same holds for $goodat.summernote('code') and textfield5.
When you use callbacks for the summernote events, you can prevent this behaviour and have more control.
$('#estado').summernote({
callbacks: {
onChange: function(contents, $editable) {
console.log('onChange:', contents, $editable);
$("#textfield4").val(contents); //populate text area
}
}
});
Read more here
Another thing that could be causing trouble, is the foreach loop containing elements with hardcoded id's. Since id's have to be unique this can give some unexpected results. Of course, when $user matches $account->user only once, everything is fine, but I usually don't take the risk.
UPDATE: added a jsfiddle here of a possible implementation.

Categories