Importing or loading a JavaScript file in Vue.js is a crucial step

I'm in need of some assistance. I've been attempting to load my javascript file and listen for changes on the checkbox when it's clicked to show or hide a password. However, I can't seem to get it to work. I've tried everything I could think of but I'm now stuck and unsure how to fix the issue.

$(document).ready(function () {
 $('#showPassword').on('click', function () {
if ($(this).prop('checked')) {
  $('#password').attr('type', 'text')
} else {
  $('#password').attr('type', 'password')
}
})



<template>
<div class="container-fluid p-0">
<div class="col-md-12 content">
<div class="col-md-6 join-container" id="join-container">
  <form class="col-md-12 col-sm-12"
  >
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" class="form-control"
             id="password" v-model="password"
             placeholder="Password">
    </div>
    <div class="form-group pl-0">
      <div class="form-check">
       <input class="form-check-input" type="checkbox"
              id="showPassword" />
       <label class="form-check-label"
              for="show-password">Show Password</label>
      </div>
    </div>
    <br>
  </form>
</div>
</div>
</template>

<script>
import Main from '../script/Index.js'

export default {
  name: 'Register',
  data: () => ({

 }),
methods: {
},
components: {
 Main
}
}
</script>

Answer №1

Your usage of jQuery event handlers (the $ bit) appears to be outside a script tag in a Vue component file, which may not produce the desired outcome.

If you intend for that code to run properly, it should be enclosed within the <script> tags of your component. However, Vue already provides event listeners (link to documentation) for functionalities like handling click events on elements. Using two frameworks for this purpose seems unnecessary.

To create a simple show password button with your existing markup, consider the following implementation focusing on Vue-specific logic:

<template>
<div>
  <input :type="passwordType" v-model="password">
  <input v-model="showPassword" type="checkbox"/>
</div>
</template>

<script>

export default {
  data() {
    return {
      showPassword: false,
      password: ''
    }
  },
  computed: {
    passwordType() {
      if (this.showPassword) {
        return 'text'
      } else {
        return 'password'
      }
    }
  }
}
</script>

Answer №2

It is not recommended to mix jQuery and Vue together as they operate on separate lifecycles.

Vue has the capability to fulfill all your requirements on its own.

To achieve this, simply link the state of your checkbox to a Vue data property and use it to control the password field's type, like so:

<input :type="passwordFieldType" class="form-control"
       id="password" v-model="password"
       placeholder="Password">

<!-- additional code here -->

<input v-model="passwordFieldType" true-value="text" false-value="password"
       class="form-check-input" type="checkbox"
       id="showPassword">
data: () => ({
  passwordFieldType: 'password'
})

For further reference, visit: https://v2.vuejs.org/v2/guide/forms.html#Checkbox-1

new Vue({
  el: '#app',
  data: () => ({
    password: '',
    passwordFieldType: 'password'
  })
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<form class="col-md-12 col-sm-12" id="app">
  <div class="form-group">
    <label for="password">Password</label>
    <input :type="passwordFieldType" class="form-control" id="password" v-model="password" placeholder="Password">
  </div>
  <div class="form-group pl-0">
    <div class="form-check">
      <input v-model="passwordFieldType" true-value="text" false-value="password"
             class="form-check-input" type="checkbox" id="showPassword" />
      <label class="form-check-label" for="show-password">Show Password</label>
    </div>
  </div>
  <br>
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to alter row colors in SQL/PHP tables

echo "<tbody"; echo "<tr>"; echo "<td>{$id}</td>";// display customer Id echo "<td> {$firstname} {$lastname}</td>"; //display customer title,firstname,lastname echo "<td>{$date->format('h:i A')}</td> ...

Positioning Images at the Top of the Screen in React Native

I have two images that I would like to display side by side at the top of the screen. <View style={styles.container}> <View style={styles.topWrapper}> <Image source={TOP_START_GRAPHIC} style={styles.topStartImage} /> ...

Configuring environment variables in Vue CLI

When using webpack, I found a way to set environment variables in my package.json as shown below: "scripts": { "dev:visualise": "webpack serve --open --config webpack.dev.js --env entry=visualise", "dev:order": & ...

What types of elements can a v-bind:is directive display?

One of the challenges I am facing involves a component that registers over 15 external components. Within the template, there is a dynamic component implemented as follows: <template> <component :is="config.name" /> </template> ...

Properties of the State Object in React Redux

I'm curious as to why my state todos were named todo instead of todos in the redux dev tools. Where did that name come from? There is no initial state, which makes me wonder. I'm currently following a Udemy course by Stephen Grider, but I am wor ...

Issue with Vue.js 2.0 transition not triggering on changing routes dynamically

I've encountered an issue where transitions are not firing on dynamic routes with parameters. For example, when navigating from /chapter/1 to /chapter/2, no transition occurs. However, when going from /chapter/1 to /profile/1, a transition does occur! ...

Exploring the Power of Angular Toastr Callback Functions

Hey there! I'm currently working with Angular Toastr to display messages on my screen. I have a setup where only two messages can be open at the same time - one for errors and another for warnings. These messages are persistent and require user intera ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Top choices for creating animations using THREE.JS

Which animations work best in three.js? Are you using additional libraries like tween.js or something else for texture animations, moving objects, and showing/hiding objects? Thank you. ...

I'm experiencing trouble with Shopify as it appears to be failing to execute

I have been attempting to incorporate a tracking pixel into my project. Thus far, I have tested the code in various environments, both with and without wrapping it in a function and deploying it using window.onload. If you would like to see the implementa ...

Converting a String to a JSON Array in NodeJS

Here's a question that bears resemblance to string-to-json-array-of-json-objects. The scenario involves the following string: "[{'Phonetype':'Pre','Phone':'918282311'},{'Phonetype':'pre',&ap ...

Guide to implementing a random number generator within a Jquery conditional statement

I am experimenting with if statements, but I'm encountering some difficulties. My goal is to assign random numbers to a variable and then trigger different actions based on a click event. Here's what I've tried so far, but it seems to be fa ...

What is the best way to use ajax to load a particular div or class from a file?

In my main.html file, there are several divs each with 2 classes. The first is their specific class and the second is a class called menu-item, which determines if an event will be triggered when clicked. For example: <div id="load-here"> </div ...

At times, the Angular Modal Dropdown may unexpectedly open in an upward direction

Dealing with an AngularJS modal that contains a dropdown menu. The menu list is quite extensive. Most of the time, around 70%, the menu drops down in the lower direction which is fine. However, approximately 30% of the time, the dropdown menu appears in ...

Having Multiple File Inputs [type=file] in one webpage

Is it possible to have two separate inputs for uploading images, each setting a different background image in a div? The second file input is: <input type='file' id='getval' name="logo" /> I want this file to be set as the back ...

Exploring the power of searching JSON data using ReactJS

After reading through the "Thinking in React" blog, I'm inspired to create something similar. Instead of filtering an array table, I want it to display the row that matches the input value. I have attempted this and created a jsfiddle example here: j ...

Different ways to alter response headers using express-http-proxy

Context In my current project, I am utilizing the express-http-proxy package to facilitate requests between a Single Page Application (SPA) and a CouchDB instance. I have opted for handling this proxy setup on a per call basis rather than creating a dedic ...

Display a custom AngularJS directive on content loaded through $http request

I'm facing a dilemma. I have created a directive app.directive('a', function() { return { restrict: 'E', link: function(scope, elem, attrs) { elem.on('click', function(e){ ...

Retrieve HTML classes within JavaScript textual templates

<!-- TEMPLATE UPLOAD --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="name"><span>{%=file.name%}</span></td> <td ...

What is the best method for storing objects in Firebase in order to easily rearrange them at a later time?

My list looks something like this: {"ids": [ { "id1": { "name": "name1", "lastname": "lastname1" } }, { "id2": { "name": "name2", "lastname": "lastname2" } }, { "id3": { "name": "name3", "l ...